问题
I'm taking a look at Rust and decided to build a small program that takes a user's input and prints it, but also want to do some math stuff with it for practice. Currently, this is how I am taking user input:
let mut number = String::new();
let input = io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
However, although I do get the correct input this way, Cargo gives me the following warning:
src/main.rs:10:9: 10:14 warning: unused variable:
input
, #[warn(unused_variables)] on by defaultsrc/main.rs:10 let input = reader.read_line(&mut number)
If I were to just use the input
variable, no matter what number I enter I would get a "2" in return when I print the number.
How can I avoid the warning? Is there another way for me to take input without creating 2 variable bindings?
回答1:
You can simply not write the value to a variable. As long as the type of the value is not marked must_use
, you can ignore the value.
let mut number = String::new();
io::stdin().read_line(&mut number)
.ok()
.expect("Failed to read line");
println!("You entered {}", number);
[commercial]
You can use the text_io crate for super short and readable input like
let i: i32 = read!()
let tup: (i32, String) = read!("{}, {}");
[/commercial]
回答2:
It creates a warning because you are allocating space for a variable that is never used.
When faced with such warning you can either replace offending variable with _
let _ = io::stdin().read_line(&mut number) ...
or as ker noted just remove the variable altogether
io::stdin().read_line(&mut number)...
The _
will also work in other situation like parameters or in match
clauses.
One additional option is to add #[allow(unused_variables)]
in the module or crate and disable unused variable warnings. Although, I don't recommend it.
来源:https://stackoverflow.com/questions/30126581/how-can-i-get-user-input-without-receiving-an-unsed-variable-warning