我正在学习Rust and Play通过一些场景来看看它是如何运行的.当将可变引用传递给函数,然后将另一个可变引用赋给它时,Rust编译器似乎希望引用的变量与最初引用的变量一样长.
但是,因为我实际上是将引用交换到其他地方的point,所以它永远不会影响调用函数的引用.它仍然会指向Foo,它是完全活着的.那么为什么foo2要和foo一样长寿呢?这看起来像是在期望替换原始引用中的引用...
struct Foo {
x: u32,
y: u32
}
fn do_something(mut foo: &mut Foo) {
foo.x = 4;
foo.y = 5;
println!("foo.x = {}\nfoo.y = {}", foo.x, foo.y);
let mut foo2 = Foo{x: 10, y: 20};
foo = &mut foo2;
println!("foo.x = {}\nfoo.y = {}", foo.x, foo.y);
}
fn main() {
let mut foo = Foo{x: 1, y: 2};
do_something(&mut foo);
println!("foo.x = {}\nfoo.y = {}", foo.x, foo.y);
}
以下是编译器所说的:
error[E0597]: `foo2` does not live long enough
--> main.rs:11:11
|
6 | fn do_something(mut foo: &mut Foo) {
| - let's call the lifetime of this reference `'1`
...
10 | let mut foo2 = Foo{x: 10, y: 20};
| -------- binding `foo2` declared here
11 | foo = &mut foo2;
| ------^^^^^^^^^
| | |
| | borrowed value does not live long enough
| assignment requires that `foo2` is borrowed for `'1`
12 | println!("foo.x = {}\nfoo.y = {}", foo.x, foo.y);
13 | }
| - `foo2` dropped here while still borrowed
error: aborting due to previous error
For more information about this error, try `rustc --explain E0597`.