Mystery "value assigned is never read" warning


#1

The following code has the following warning. Why? It seems like the value is obviously read.

    pub fn line(&mut self) -> io::Result<Option<&[u8]>> {
        let mut len = 0;
        loop {
            match self.find_nl() {
                Some(l) => { len = l; break; }
                None => {
                    if try!(self.fill_buf()) == 0 {
                        return Ok(None)
                    }
                }
            };
        }
        return Ok(Some(&self.buf[self.pos..self.pos+len]));
    }
src/line_reader.rs:21:13: 21:20 warning: value assigned to `len` is never read, #[warn(unused_assignments)] on by default
src/line_reader.rs:21         let mut len = 0;
                                  ^~~~~~~
$ rustc --version
rustc 1.8.0 (db2939409 2016-04-11)

#2

This refers only to the initial 0, which is indeed never read - since to get to the return Ok(Some(...)), the loop must have been exited in the break. Just do let mut len; and rustc is happy.


#3

In fact, you don’t even need mut. Just let len; is enough, because the variable is never mutated after it’s assigned.


#4

In my opinion the error should point to the 0 and not the binding, as this is super confusing and happened to me before too.


#5

In my opinion the error should point to the 0 and not the binding.

Filed as https://github.com/rust-lang/rust/issues/33536.


#6

Thanks! I never woulda guessed let len; is valid Rust code!