Mystery "value assigned is never read" warning

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)

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.

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

2 Likes

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.

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

Filed as "value assigned is never used" should point to value, not binding · Issue #33536 · rust-lang/rust · GitHub.

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