2016-07-09 10 views
1

番号48〜57のベクトルを作成してランダムにシャッフルしようとしています。ベクトルを作成してシャッフルすることができません

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

答えて

5
  1. collectはあなたに収集したいどのような種類を知っている必要があります:私はここにコードがあります以下のエラー

    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); 
          ^~~~~~~ 
    

    に実行していますよ。その様子からは、Vecをしたい:

    let mut secret_num: Vec<_> = (48..58).collect(); 
    
  2. あなたはそれを持っていることが有効ではありませんslice無サイズの種類を、になるだろうので、この変数の宣言で&mutを使用したくありません。実際、この行は冗長です。

    let &mut slice = secret_num.as_mut_slice(); 
    
  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` 
    
  4. 全くloopの必要はありません。それを除く。問題の原因を理解するのに役立つ質問をするときにはMCVEを作り、問題の原因を理解するのに役立ちます。あなたの実際のプログラムでは、乱数発生器を一度、のループの前にオーバーヘッドを避けるために取得する必要があります。

extern crate rand; 

use rand::Rng; 

fn main() { 
    let mut secret_num: Vec<_> = (48..58).collect(); 
    let mut rng = rand::thread_rng(); 

    rng.shuffle(&mut secret_num); 

    println!("{:?}", secret_num); 
} 
関連する問題