hello,

last time I made a fibonacci series generator in Rust and now I have made something different :)

use std::io;

fn main() {
    let mut input: String = String::new();
    let stdin = io::stdin();

    let x = rand::random::<u32>() % 101;
    let mut attempts = 0;

    loop {
        println!("Guess a number from 0 to 100:");
        stdin.read_line(&mut input);
        input = input.to_string().replace("\n", ""); // removing the \n
        let user_input: u32 = input.parse::<u32>().unwrap();
        if x == user_input {
            println!("You won! attempts: {attempts}");
            break;
        }
        else if x < user_input {
            println!("too big");
            attempts += 1;
        }
        else {
            println!("too small");
            attempts += 1;
        }
        input.clear()
    }
}

feel free to give me suggestion :)

  • FizzyOrange@programming.dev
    link
    fedilink
    arrow-up
    7
    ·
    3 days ago

    Some suggestions:

    1. Declare input in the loop. That limits scope which is basically always a good idea.
    2. Trim the newline like
    let input = input.trim();
    

    This is better in several ways:

    1. Simpler
    2. Doesn’t allocate a new string.
    3. Removes all whitespace at the start and end.
    4. It makes input immutable after that line.

    Also attempts is never read - you should have got a compiler warning about that.

    Otherwise, good work.

    • whoareu@lemmy.caOP
      link
      fedilink
      arrow-up
      3
      ·
      3 days ago

      Thank you for the suggestions.

      attempts is used to display total attempts when user wins the game so it is used in the program, I don’t see any warnings from compiler.

    • nous@programming.dev
      link
      fedilink
      English
      arrow-up
      2
      ·
      3 days ago

      Declare input in the loop. That limits scope which is basically always a good idea.

      There is good reason to not do this. Though in this case it won’t make much difference as performance is not an issue. But by having it outside the loop it allows the allocation of the string to be reused and in more complex programs is typically what you would want to do - allocate once outside the loop and reuse that inside.

      In this case waiting on user input is going to outweigh any performance benefit I would not call it out as bad practice either.

      • FizzyOrange@programming.dev
        link
        fedilink
        arrow-up
        2
        ·
        3 days ago

        Yes this is true, but it’s a little advanced for this level so I didn’t mention it. Probably better for beginners to focus on good code style than optimal performance.