Search code examples
rustinitializationvariable-assignment

How do I guarantee the rust compiler that a certain variable will get initialized in a for loop?


This question is in relation to the question asked here: How to declare a variable but not assign it?

My problem is slightly different. MRE:

let var: MyGenericType;
for value in vec_of_values_of_my_generic_type {
    // one of the values is mathematically guaranteed to meet this condition because the vector is special
    if <value meets a certain condition> {
        var = value;
    }
}

<use var>

Error:

error[E0381]: used binding `var` is possibly-uninitialized
   --> example/src/lib.rs:127:23
    |
120 |             let var: MyGenericType;
    |                 -- binding declared here but left uninitialized
...
123 |                     var = value;
    |                     -- binding initialized here in some conditions
...
127 |             foo(var);
    |                       ^^ `var` used here but it is possibly-uninitialized

How do I fix this?


Solution

  • Use the right tool for the job, here that would be Iterator::find, instead of manually looping:

    let var = vec_of_values_of_my_generic_type
        .into_iter()
        .find(|value| <value meets a certain condition>)
        .unwrap();