For below code snippet, rust compiler with cargo check is giving wrong warning
I am using rust version rustc 1.48.0 (7eac88abb 2020-11-16) and
cargo version cargo 1.48.0 (65cbdd2dc 2020-10-14)
Here is the smallest possible code to replicate the issue.
fn main() {
let mut input = String::new();
let result = Some("test");
match result {
Some(value) => input = value.to_string(),
None => return,
}
println!("The value is {}", input);
}
Below is the warning message:
warning: value assigned to `input` is never read
--> src/main.rs:2:9
|
2 | let mut input = String::new();
| ^^^^^^^^^
|
= note: `#[warn(unused_assignments)]` on by default
= help: maybe it is overwritten before being read?
warning: 1 warning emitted
Is this valid thing or I need to report bug for this. Also where to report bugs for such thing.
The error isn't wrong. The very first value that you assign input to, String::new() is never used. You reassign input to value.to_string() without ever reading the String::new().
The following code produces no warning:
fn main() {
let input;
let result = Some("test");
match result {
Some(value) => input = value.to_string(),
None => return,
}
println!("The value is {}", input);
}
fn main() {
let result = Some("test");
let input = match result {
Some(value) => value.to_string(),
None => return,
};
println!("The value is {}", input);
}
--- 2025 Edit ---
Now, we also have the let-else syntax:
fn main() {
let result = Some("test");
let Some(value) = result else {
return;
};
println!("The value is {}", value);
}