【发布时间】:2020-06-25 07:30:28
【问题描述】:
每次我接受用户输入时,我都会创建一个新变量(通过阴影)来获取输入。我认为这是低效的,不是阴影的目的,我还能如何有效地重用变量输入?
如果没有阴影,它会给出错误cannot borrow "input" as mutable because it is also borrowed as immutable。据我了解,接受用户输入需要可变引用。
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
}
来自 Java,我对借用如何工作以及何时使用影子是个好主意感到困惑。我了解旧值仍然存在,并且对它的任何引用都意味着如果您不再需要旧值,那么您将无缘无故地占用资源。任何建议都有帮助,谢谢。
【问题讨论】:
标签: rust