On 16/01/2014 16:13, Tommy M. McGuire wrote:
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)?


Something immutable can become mutable when it’s moved. Matching an enum member without "ref" moves.

It would be a different story (I think) if your pattern was Some(ref mut f).

--
Simon Sapin
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to