Skip to content

Deprecated Methods in Guessing Game Example – Suggested Modernization #4481

@mrhouzlane

Description

@mrhouzlane

For this URL

Current code example :

use std::io;

use rand::Rng;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("The secret number is: {secret_number}");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {guess}");
}

Warnings/Errors:

 use of deprecated function `rand::thread_rng`: Renamed to `rng`
`#[warn(deprecated)]` on by defaultrustc[Click for full compiler diagnostic](rust-analyzer-diagnostics-view:/diagnostic%20message%20[0]?0#file:///Users/mehdi/rust01/guessing_game/src/main.rs)
use of deprecated method `rand::Rng::gen_range`: Renamed to `random_range`rustc[Click for full compiler diagnostic](rust-analyzer-diagnostics-view:/diagnostic%20message%20[1]?1#file:///Users/mehdi/rust01/guessing_game/src/main.rs)

The code sample in the guessing game tutorial appears to use deprecated methods, which can be confusing for new learners. Please update the code to reflect current best practices with the rand crate. For reference, here is the updated version that works:

use std::io;
use rand::*Rng*;
fn main() {
    println!("Guess the number!");
    let secret_number = rand::rng().random_range(1..=100);
    println!("The secret number is: {secret_number}");
    println!("Please input your guess.");
    let mut guess = String::new();
    io::stdin().read_line(&mut guess).expect("Failed to read line");
    println!("You guessed: {guess}");
}

Could the example be updated, and any change in the rand crate be linked in the tutorial for further clarity? Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions