【发布时间】:2014-01-22 04:38:00
【问题描述】:
use std::util::replace;
假设我们有这些结构:
struct Foo {
a: ~[Baz],
}
struct Bar {
a: ~[Quux],
}
struct Baz {
x: bool
}
struct Quux {
x: bool,
y: Bar,
}
以下工作正常:
let mut foo = Foo{a: ~[Baz {x: true},
Baz {x: false}]};
println!("{}, {}", foo.a[0].x, foo.a[1].x); // true false
replace(&mut foo.a[0], foo.a[1]);
println!("{}, {}", foo.a[0].x, foo.a[1].x); // false false
但是,这不起作用:
let mut bar = Bar{a: ~[Quux {x: true, y: Bar {a: ~[]} },
Quux {x: false, y: Bar {a: ~[]} }]
};
println!("{}, {}", bar.a[0].x, bar.a[1].x); // true false
replace(&mut bar.a[0], bar.a[1]);
}
编译器给出的错误是:
foobar_borrow2.rs:35:28: 35:36 error: cannot move out of `(*bar.a)[]` because it is borrowed
foobar_borrow2.rs:35 replace(&mut bar.a[0], bar.a[1]);
^~~~~~~~
foobar_borrow2.rs:35:13: 35:26 note: borrow of `(*bar.a)[]` occurs here
foobar_borrow2.rs:35 replace(&mut bar.a[0], bar.a[1]);
^~~~~~~~~~~~~
我不明白这是什么意思。这似乎与前一个案例相似,它有效。为什么将Bar 字段添加到Quux 会导致它失败?
【问题讨论】:
标签: rust