How to declare a variable but not assign it?


I want to declare acceptable_set and use it. But an empty vector is assigned to it. So the compiler warns. How to declare a variable and do not assign it?

let mut acceptable_set: Vec<String> = Vec::new();
if opt.acceptable_set.is_none() {
    acceptable_set = crate::builtin_words::ACCEPTABLE
        .map(|x| x.to_string())
} else {
    acceptable_set = get_acceptable_set(opt)
warning: value assigned to `acceptable_set` is never read
  --> src/
27 |     let mut acceptable_set: Vec<String> = Vec::new();
   |             ^^^^^^^^^^^^^^
   = note: `#[warn(unused_assignments)]` on by default
   = help: maybe it is overwritten before being read?

>Solution :

Instead of declaring an uninitialised variable like this

let var;
if condition {
  var = value1;
} else {
  var = value2;

you could directly initialise the variable with the alternative.

let var = if condition { value1 } else { value2 };

Your variable does not even need the mut keyword (except if you want to mutate it afterwards).

And since in the example of your question you seem to test against an Option (.is_none()), you could use this form.

fn main() {
    let value1 = 12;
    let value2 = 34;
    let opt = Some(987);
    let var = if let Some(opt_value) = opt {
        value1 + opt_value // use the data in the option
    } else {
        value2 // the option contains nothing, use a default value
    println!("var {:?}", var);

See also map_or_else().

Leave a ReplyCancel reply