The Rules of References
Let’s recap what we’ve discussed about references:
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid.
I saw this question: How to make a Rust mutable reference immutable?
Here is code:
fn main() {
let data = &mut vec![1, 2, 3];
let x = &*data;
println!("{:?}-{:p}, {:?}-{:p}", x, x, data, data); // same address
}
Output:
It seems that the anonymous object(vec![1, 2, 3]
) contain both mutable reference(data
) and immutable reference(x
, *data
is anonymous object vec![1, 2, 3]
).
But, when I tried to assign the vec![1, 2, 3]
to variable v
in following code, I got an error:
fn main() {
let v = vec![1, 2, 3];
let data = &mut v;
let x = &*data;
println!("{:?}-{:p}, {:?}-{:p}", x, x, data, data);
}
Ouput:
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable
--> src/main.rs:5:16
|
4 | let v = vec![1, 2, 3];
| - help: consider changing this to be mutable: `mut v`
5 | let data = &mut v;
| ^^^^^^ cannot borrow as mutable
For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground` due to previous error
What is the difference between these? Please help me. Thanks.
t