Search code examples
rustshadowing

Compiler thinks boolean variable is unused


I'm playing with session types for rust, and i have a pretty simple function that does that following:

fn srv(c: Chan<(), Server>){
    let (c, n) = c.recv();
    let tmp = false;
    if n % 2 == 0 {
        let tmp = true;
    } else {
        let tmp = false;
    }
    let c = c.send(tmp);
    
    let (c, s) = c.recv();

    println!("server side: {}", s);


    c.close();
}

When I try to compile this, the rust compiler thinks that the tmp variable is unused. This seems strange to me, since I am passing it to the recv function.

warning: unused variable: `tmp`
  --> src/main.rs:25:13
   |
25 |         let tmp = false;
   |             ^^^ help: if this is intentional, prefix it with an underscore: `_tmp`

I tried playing around by making it mutable, which didnt help.

If I print it, the warning goes away. But why is it even there when I am using it for the send function?


Solution

  • since I am passing it to the recv function.

    No, that is the other tmp defined outside the if/else scopes.

    What you want:

    let mut tmp = false;
    if n % 2 == 0 {
        tmp = true;
    } else {
        tmp = false;
    }
    

    Or:

    let tmp;
    if n % 2 == 0 {
        tmp = true;
    } else {
        tmp = false;
    }
    

    Or:

    let tmp = if n % 2 == 0 {
        true
    } else {
        false
    };
    

    Or:

    let tmp = n % 2 == 0;