Every time I take user input I created a new variable (via shadowing) to get the input. I think this is inefficient and not the purpose of shadowing, how else can I efficiently reuse the variable input?
Without shadowing it gives the error cannot borrow "input" as mutable because it is also borrowed as immutable
. As I understand taking user input requires a mutable reference.
use std::io; // Import for IO
fn main() {
let name: &str; // Variables
let balance: f32; // Variables
let interest: f32; // Variables
let mut input = String::new(); // Variables
println!("Please enter your name: "); // Print
io::stdin().read_line(&mut input).expect("failed to read from stdin");
name = input.trim();
println!("Please enter your bank account balance: "); // Print
loop {
let mut input = String::new(); // Remove this and I get an error
io::stdin().read_line(&mut input).expect("failed to read from stdin");
match input.trim().parse::<f32>() {
Ok(_) => {
balance = input.trim().parse().unwrap();
break;
},
Err(_) => println!("Your balance cannot contain letters or symbols"),};
}
}
println!("Please enter your interest rate percent: "); // Print
loop {
let mut input = String::new(); // Remove this and I get an error
io::stdin().read_line(&mut input).expect("failed to read from stdin");
match input.trim().parse::<f32>() {
Ok(_) => {
interest = input.trim().parse().unwrap();
break;
},
Err(_) => println!("Your balance cannot contain letters or symbols"),};
}
}
println!("{}, your gain from interest is : ${}", name, (interest * balance * 0.01)); // Print
}
Coming from Java I am perplexed on how borrowing works and when shadowing is a good idea. I understand that the old value still exists and any references to it which means if you don't need the old value anymore then you're taking up resources for no reason. Any advice is helpful, thanks.