Search code examples
rustwarningsspawn

Rust — why is there a warning "value captured by `online` is never read" here?


Why does the Rust compiler issue this warning?

value captured by online is never read

use std::{thread, time::Duration};
use rand::Rng;

fn main() {
    let mut online = false;

    thread::spawn(move || {
        loop {
            if let Some(_) = get_rand_option() {
                online = true;    // why is there a warning here?
            } else {
                online = false;
            }

            if online {           // is the value not being read here?
                println!("Yee");
            } else {
                println!("...");
            }
        }
    });

    thread::sleep(Duration::from_millis(100000));
}

fn get_rand_option() -> Option<i32> {
    rand::thread_rng().gen::<Option<i32>>()
}

Solution

  • Rust is smart enough to know that you will initialize that variable before using it, so it tells you that giving it a value before that is superfluous. I also moved the variable declaration inside the closure, since it is permanently moved inside it anyway otherwise.

    Note that for this minimal example, you might as well just declare online inside the loop, since you never break out of it or use the value from a previous iteration: let online = if let …

    use std::{thread, time::Duration};
    use rand::Rng;
    
    fn main() {
    
        thread::spawn(|| {
            let mut online: bool;
            loop {
                // using the fact that ‘if let’ is an expression
                online = if let Some(_) = get_rand_option() {
                    true
                } else {
                    false
                };
    
                if online {         
                    println!("Yee");
                } else {
                    println!("...");
                }
            }
        });
    
        thread::sleep(Duration::from_millis(100000));
    }
    
    fn get_rand_option() -> Option<i32> {
        rand::thread_rng().gen::<Option<i32>>()
    }