无法创建向量并对其进行洗牌 [英] Unable to create a vector and shuffle it

查看:46
本文介绍了无法创建向量并对其进行洗牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个数字为 48 到 57 的向量,然后对其进行随机洗牌.我遇到了以下错误

I'm trying to create a vector with the numbers 48 to 57 and then randomly shuffle it. I'm running into the following errors

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!");
}

推荐答案

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

  1. collect needs to know what type you wish to collect into. From the looks of it, you want a Vec:

let mut secret_num: Vec<_> = (48..58).collect();

  • 您不想在此变量的声明中使用 &mut ,因为这会使 slice 成为无效的无大小类型具有.其实这条线是多余的.

  • You don't want to use &mut in the declaration of this variable because that would make slice an unsized type, which isn't valid to have. In fact, this line is redundant.

    let &mut slice = secret_num.as_mut_slice();
    

  • 特征必须被纳入范围.您已经收到的错误消息应该已经告诉您这一点.Rust 大部分时间都有很好的错误信息.你应该阅读它们:

  • Traits must be brought into scope. The error message you are already getting should already be telling you this. Rust has pretty good error messages most of the time. You should read them:

    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`
    

  • 根本不需要循环;去掉它.在提出问题时制作 MCVE 以帮助您了解问题的根源并帮助其他人回答问题.在您的实际程序中,您应该在循环之前获得随机数生成器一次以避免开销.

  • There's no need for a loop at all; remove it. Produce an MCVE when asking a question to help you understand the source of the problem and others to answer it. In your real program, you should get the random number generator once before the loop to avoid overhead.

    自从你最初提出这个问题以来,rand 已经重新组织了他们的代码.shuffle 现在是 SliceRandom 特性.

    Since you originally asked the question, rand has reorganized their code. shuffle is now part of the SliceRandom trait.

    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);
    }
    

    这篇关于无法创建向量并对其进行洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆