官术网_书友最值得收藏!

How to do it...

  1. Open the Cargo.toml file that was generated earlier for you
  2. Under [dependencies], add the following line:
rand = "0.3"
  1. If you want, you can go to rand's crates.io page (https://crates.io/crates/rand) to check for the newest version and use that one instead
  2. In the bin folder, create a file called rand.rs

  3. Add the following code and run it with cargo run --bin rand:

1   extern crate rand;
2
3 fn main() {
4 // random_num1 will be any integer between
5 // std::i32::MIN and std::i32::MAX
6 let random_num1 = rand::random::<i32>();
7 println!("random_num1: {}", random_num1);
8 let random_num2: i32 = rand::random();
9 println!("random_num2: {}", random_num2);
10 // The initialization of random_num1 and random_num2
11 // is equivalent.
12
13 // Every primitive data type can be randomized
14 let random_char = rand::random::<char>();
15 // Altough random_char will probably not be
16 // representable on most operating systems
17 println!("random_char: {}", random_char);
18
19
20 use rand::Rng;
21 // We can use a reusable generator
22 let mut rng = rand::thread_rng();
23 // This is equivalent to rand::random()
24 if rng.gen() {
25 println!("This message has a 50-50 chance of being
printed");
26 }
27 // A generator enables us to use ranges
28 // random_num3 will be between 0 and 9
29 let random_num3 = rng.gen_range(0, 10);
30 println!("random_num3: {}", random_num3);
31
32 // random_float will be between 0.0 and 0.999999999999...
33 let random_float = rng.gen_range(0.0, 1.0);
34 println!("random_float: {}", random_float);
35
36 // Per default, the generator uses a uniform distribution,
37 // which should be good enough for nearly all of your
38 // use cases. If you require a particular distribution,
39 // you specify it when creating the generator:
40 let mut chacha_rng = rand::ChaChaRng::new_unseeded();
41 let random_chacha_num = chacha_rng.gen::<i32>();
42 println!("random_chacha_num: {}", random_chacha_num);
43 }
主站蜘蛛池模板: 隆林| 平阴县| 永登县| 秭归县| 沙坪坝区| 灌阳县| 东兰县| 丹凤县| 西吉县| 保定市| 梁山县| 永平县| 库尔勒市| 宣恩县| 奉新县| 潼南县| 阜康市| 婺源县| 定日县| 天祝| 临泽县| 汤阴县| 成安县| 广饶县| 香港 | 平罗县| 宝山区| 河源市| 泉州市| 赫章县| 禹城市| 北海市| 岳普湖县| 滦平县| 东阿县| 天全县| 绥中县| 陆川县| 云南省| 青海省| 武宁县|