[rust-dev] Something odd I just noticed with mut and pattern matching

Kevin Ballard kevin at sb.org
Thu Jan 16 11:37:33 PST 2014


On Jan 16, 2014, at 8:13 AM, Tommy M. McGuire <mcguire at crsr.net> wrote:

>    let file = File::open_mode(&Path::new("test"), Truncate, Write);
> 
>    match file {
>        Some(mut f) => f.write_str( "hello" ),
>        None => fail!("not a file")
>    }

This is fine, because you’re consuming `file` and moving the contained value into a new mutable `f` variable. It’s basically the same as

    if file.is_some() {
        let mut f = file.unwrap();
        …
    } else {
        fail!(“..”);
    }

> works, while
> 
>    let mut file = File::open_mode(&Path::new("test"), Truncate, Write);
> 
>    match file {
>        Some(mut f) => f.write_str( "hello" ),
>        None => fail!("not a file")
>    }
> 
> results in a "variable does not need to be mutable" warning.

The warning here is because `file` doesn’t need to be mutable.

> Shouldn't the third option also fail (and possibly the second option
> succeed)?

The first two failed because the variable that needed to be mutable, `f`, was not mutable the second two succeeded because it was.

As Simon has already pointed out, if you tried to use a by-ref binding it would fail, because you can’t take a mutable borrow of an immutable variable. But you didn’t do that, you moved the value, and moving from an immutable variable into a mutable one is perfectly legal.

-Kevin


More information about the Rust-dev mailing list