Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        .to_vec()
        .iter_mut()
        .map(|x| x.to_string())
        .collect();
} else {
    acceptable_set = get_acceptable_set(opt)
}
warning: value assigned to `acceptable_set` is never read
  --> src/basic_function.rs:27:13
   |
27 |     let mut acceptable_set: Vec<String> = Vec::new();
   |             ^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_assignments)]` on by default
   = help: maybe it is overwritten before being read?
like image 650
zhaozk Avatar asked Oct 23 '25 17:10

zhaozk


1 Answers

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().

like image 149
prog-fh Avatar answered Oct 26 '25 08:10

prog-fh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!