やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

Rustで乱数を生成する(rand)

 randクレートをダウンロードして。

成果物

手順

  1. プロジェクト作成
  2. 依存クレート追加
  3. クレート利用
  4. クレート入手
  5. 実行

1. プロジェクト作成

$ cargo new rand20190519 --bin

2.依存クレート追加

Cargo.toml

[dependencies]
rand="0.6.5"

3.クレート利用

main.rs

extern crate rand;
use rand::Rng;
fn main() {
    let secret_number = rand::thread_rng().gen_range(1, 101);
    println!("Secret number is {}", secret_number);
}

4.クレート入手

$ cargo run
    Updating crates.io index
  Downloaded rand v0.6.5
  Downloaded rand_hc v0.1.0
  Downloaded rand_pcg v0.1.2
  Downloaded rand_chacha v0.1.1
  Downloaded rand_isaac v0.1.1
  Downloaded rand_os v0.1.3
  Downloaded rand_jitter v0.1.4
  Downloaded rand_core v0.4.0
  Downloaded autocfg v0.1.2
  Downloaded rand_xorshift v0.1.1
  Downloaded rand_core v0.3.1
  Downloaded libc v0.2.55
   Compiling libc v0.2.55
   Compiling autocfg v0.1.2
   Compiling rand_core v0.4.0
   Compiling rand_core v0.3.1
   Compiling rand_jitter v0.1.4
   Compiling rand_chacha v0.1.1
   Compiling rand_pcg v0.1.2
   Compiling rand v0.6.5
   Compiling rand_hc v0.1.0
   Compiling rand_xorshift v0.1.1
   Compiling rand_isaac v0.1.1
   Compiling rand_os v0.1.3
   Compiling guessing_game v0.1.0 (/tmp/work/Rust.GuessingGame.20190519093331/src/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 2m 02s
     Running `/tmp/work/Rust.GuessingGame.20190519093331/src/guessing_game/target/debug/guessing_game`
Secret number is 71

 cargo runすると依存クレートを入手する。(初回のみ)

5.実行

$ cargo run
Secret number is 74

参考

対象環境

$ uname -a
Linux raspberrypi 4.14.98-v7+ #1200 SMP Tue Feb 12 20:27:48 GMT 2019 armv7l GNU/Linux

前回まで