Wrong warning message in rust

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.

Why is it wrong?

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);
}
6 Likes

Ohh, I got it now. I thought that if we declare variable then its mandatory to initialize it.
Thank you.

It's mandatory to initialize a variable if you're trying to read it, or put it into a structure. This variable:

let x: String;

Is in a kind of limbo "write-once-only" state.

The more idiomatic version would be:

fn main() {
    let result = Some("test");
    let input = match result {
        Some(value) => value.to_string(),
        None => return,
    };

    println!("The value is {}", input);
}
12 Likes