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 :)
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.
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.