Random 无法创建向量并将其洗牌

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

我试图创建一个数字为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 `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();
    
  • 特征必须纳入范围。您已经收到的错误消息应该已经告诉您了。Rust大多数时候都有很好的错误消息。你应该读一下:

    帮助: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);
    }