Discussion:
[rust-dev] type annotaion of &mut
Taku Masa
2014-09-21 08:10:30 UTC
Permalink
This is very simple code about mutable borrow.

code1 is compiled, but code2 is not compiled.
difference of them is `let b` has explicit type-annotation or not.
In this case, why is explicit annotation needed?

//code1
fn main(){
let a = &mut 10i;

{
let b:&mut int = a;
*b = 11i;
}

println!("{}",a);
}

//code2
fn main(){
let a = &mut 10i;

{
let b = a;
*b = 11i;
}

println!("{}",a);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140921/5fc9a0a5/attachment.html>
Steve Klabnik
2014-09-22 17:54:44 UTC
Permalink
Because you need to make b mutable to change its value. Rust's
variable bindings are immutable by default.
Tim Kuehn
2014-09-22 18:35:53 UTC
Permalink
That doesn't seem to be what the compilation error says:

mut.rs:10:19: 10:20 error: use of moved value: `a`
mut.rs:10 println!("{}",a);
^
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
mut.rs:10:5: 10:22 note: expansion site
mut.rs:6:13: 6:14 note: `a` moved here because it has type `&mut int`,
which is moved by default (use `ref` to override)
mut.rs:6 let b = a;

It isn't intuitive that type-annotating `b` would make this error go away.

On Mon, Sep 22, 2014 at 10:54 AM, Steve Klabnik <steve at steveklabnik.com>
Post by Steve Klabnik
Because you need to make b mutable to change its value. Rust's
variable bindings are immutable by default.
_______________________________________________
Rust-dev mailing list
Rust-dev at mozilla.org
https://mail.mozilla.org/listinfo/rust-dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140922/54f5153a/attachment.html>
Loading...