无法创建矢量并将其随机播放

KDN*_*KDN 1 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 `rand::ThreadRng` in the current scope
        rng.shuffle(&mut slice);
            ^~~~~~~
Run Code Online (Sandbox Code Playgroud)

这是代码:

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!");
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 5

  1. collect需要知道您希望收集的类型.从它的外观来看,你想要一个Vec:

    let mut secret_num: Vec<_> = (48..58).collect();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您不希望&mut在此变量的声明中使用,因为这将生成slice一个无效的类型,这是无效的.实际上,这条线是多余的.

    let &mut slice = secret_num.as_mut_slice();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 必须将特征纳入范围.您已经收到的错误消息应该已经告诉您了.Rust大多数时候都有很好的错误信息.你应该阅读它们:

    help: items from traits can only be used if the trait is in scope;
          the following trait is implemented but not in scope,
          perhaps add a `use` for it:
    help: candidate #1: `use rand::Rng`
    
    Run Code Online (Sandbox Code Playgroud)
  4. 根本不需要loop; 去掉它.在提问时帮助您了解问题的根源以及其他人来回答问题,请制作MCVE.在您的真实程序中,您应该在循环之前获取一次随机数生成器以避免开销.

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);
}
Run Code Online (Sandbox Code Playgroud)