我有一个元素是a的向量(String, String)
.我如何随机选择其中一个元素?
你想要rand
箱子,特别是choose
方法.
use rand::seq::SliceRandom; // 0.6.5 fn main() { let vs = vec![0, 1, 2, 3, 4]; println!("{:?}", vs.choose(&mut rand::thread_rng())); }
使用choose_multiple
:
use rand::seq::SliceRandom; // 0.6.5 fn main() { let samples = vec!["hi", "this", "is", "a", "test!"]; let sample: Vec<_> = samples .choose_multiple(&mut rand::thread_rng(), 1) .collect(); println!("{:?}", sample); }