zhaozk
zhaozk

Reputation: 307

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?

Upvotes: 3

Views: 3739

Answers (2)

Chad
Chad

Reputation: 1978

Yes, direct initialization is the right answer in many cases. But in more complex situations where direct initialization doesn't make sense, I recently learned that it's possible to use let without initialization (see Rust reference).

For example, the following code snippet will not produce an error or warning (as long as flag is used later on):

let flag;
if a < b { flag = true; } else { flag = false; }

(Yes, this code should use direction initialization as well. The point is to show that let without initialization is possible when it makes sense.)

Upvotes: 0

prog-fh
prog-fh

Reputation: 16785

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

Upvotes: 9

Related Questions