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

Tommy M. McGuire mcguire at crsr.net
Thu Jan 16 08:13:07 PST 2014


I found something odd with mutablity and pattern matching.

    let file = File::open_mode(&Path::new("test"), Truncate, Write);

    match file {
        Some(f) => f.write_str( "hello" ),
        None => fail!("not a file")
    }

results in a "cannot borrow immutable local variable as mutable" error,
as expected. But,

    let mut file = File::open_mode(&Path::new("test"), Truncate, Write);

    match file {
        Some(f) => f.write_str( "hello" ),
        None => fail!("not a file")
    }

also results in a "cannot borrow immutable local variable as mutable"
error, and

    let file = File::open_mode(&Path::new("test"), Truncate, Write);

    match file {
        Some(mut f) => f.write_str( "hello" ),
        None => fail!("not a file")
    }

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.

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




-- 
Tommy M. McGuire
mcguire at crsr.net


More information about the Rust-dev mailing list