How can I get a random number in Rust 1.0?

后端 未结 1 553
悲哀的现实
悲哀的现实 2021-02-12 12:37

I tried

use std::rand::{task_rng, Rng};

fn main() {
    // a number from [-40.0, 13000.0)
    let num: f64 = task_rng().gen_range(-40.0, 1.3e4);
    println!(\"         


        
1条回答
  •  死守一世寂寞
    2021-02-12 12:45

    In the far past, the rand crate was part of the standard library but has long since been extracted to a crate. This crate should be the one you use:

    Specify a Cargo.toml:

    [package]
    name = "stackoverflow"
    version = "0.0.1"
    authors = ["A. Developer "]
    
    [dependencies]
    rand = "0.7.0" # Or a newer version
    

    Then your example code works:

    use rand::Rng; // 0.7.2
    
    fn main() {
        let mut rng = rand::thread_rng();
        if rng.gen() { // random bool
            println!("i32: {}, u32: {}", rng.gen::(), rng.gen::())
        }
        let tuple = rand::random::<(f64, char)>();
        println!("{:?}", tuple)
    }
    

    With the output:

    $ cargo run
         Running `target/debug/so`
    i32: 1819776837, u32: 3293137459
    (0.6052759716514547, '\u{69a69}')
    
    $ cargo run
         Running `target/debug/so`
    (0.23882541338214436, '\u{10deee}')
    

    Why were these useful functions removed from stdlib?

    Rust has a philosophy of placing as much as possible into crates instead of the standard library. This allows each piece of code to grow and evolve at a different rate than the standard library and also allows the code to stop being used without forcing it to be maintained forever.

    A common example is the sequence of HTTP libraries in Python. There are multiple packages that all do the same thing in different ways and the Python maintainers have to keep all of them to provide backwards compatibility.

    Crates allow this particular outcome to be avoided. If a crate truly stabilizes for a long time, I'm sure it could be re-added to the standard library.

    0 讨论(0)
提交回复
热议问题