Random 无法创建向量并将其洗牌
我试图创建一个数字为48到57的向量,然后随机洗牌。我遇到了以下错误Random 无法创建向量并将其洗牌,random,rust,Random,Rust,我试图创建一个数字为48到57的向量,然后随机洗牌。我遇到了以下错误 error: the type of this value must be known in this context let &mut slice = secret_num.as_mut_slice(); ^~~~~~~~~~~~~~~~~~~~~~~~~ error: no method named `shuffle` found for type
error: the type of this value must be known in this context
let &mut slice = secret_num.as_mut_slice();
^~~~~~~~~~~~~~~~~~~~~~~~~
error: no method named `shuffle` found for type `rand::ThreadRng` in the current scope
rng.shuffle(&mut slice);
^~~~~~~
代码如下:
extern crate rand;
fn main() {
//Main game loop
loop{
let mut secret_num = (48..58).collect();
let &mut slice = secret_num.as_mut_slice();
let mut rng = rand::thread_rng();
rng.shuffle(&mut slice);
println!("{:?}", secret_num);
break;
}
println!("Hello, world!");
}
collect
需要知道您希望收集到的类型。从外观上看,您需要一个Vec
:
let mut secret_num: Vec<_> = (48..58).collect();
帮助:traits中的项目只能在traits在范围内时使用;
以下特性已实现,但不在范围内,
或许可以为它添加一个“use”:
帮助:候选者#1:`use rand::Rng`
循环
;移除它。在提出问题时,制作一个帮助你理解问题来源和其他人回答问题的句子。在实际程序中,应该在循环之前获得一次随机数生成器,以避免开销使用rand::seq::SliceRandom;//0.6.5
fn main(){
让mut secret_num:Vec=(48..58).collect();
让mut rng=rand::thread_rng();
秘密数洗牌(&mut rng);
println!(“{:?}”,secret_num);
}
let &mut slice = secret_num.as_mut_slice();
use rand::seq::SliceRandom; // 0.6.5
fn main() {
let mut secret_num: Vec<_> = (48..58).collect();
let mut rng = rand::thread_rng();
secret_num.shuffle(&mut rng);
println!("{:?}", secret_num);
}