如何将可变特征对象引用移动到框中?例如我也许会期待
struct A {a:i32}
trait B {
fn dummy(&self) {}
}
impl B for A {}
fn accept_b(x:&mut B) -> Box<B> {
Box::new(*x)
}
fn main() {
let mut a = A{a:0};
accept_b(&a);
}
... 可以工作,但它会出错
<anon>:8:5: 8:13 error: the trait `core::marker::Sized` is not implemented for the type `B` [E0277]
<anon>:8 Box::new(*x)
^~~~~~~~
<anon>:8:5: 8:13 note: `B` does not have a constant size known at compile-time
<anon>:8 Box::new(*x)
^~~~~~~~
<anon>:8:14: 8:16 error: cannot infer an appropriate lifetime due to conflicting requirements
<anon>:8 Box::new(*x)
^~
<anon>:7:33: 9:2 note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 7:32...
<anon>:7 fn accept_b(x:&mut B) -> Box<B> {
<anon>:8 Box::new(*x)
<anon>:9 }
<anon>:8:14: 8:16 note: ...so that expression is assignable (expected `B`, found `B`)
<anon>:8 Box::new(*x)
^~
note: but, the lifetime must be valid for the static lifetime...
<anon>:8:5: 8:17 note: ...so that it can be closed over into an object
<anon>:8 Box::new(*x)
^~~~~~~~~~~~
<anon>:13:14: 13:16 error: mismatched types:
expected `&mut B`,
found `&A`
(values differ in mutability) [E0308]
<anon>:13 accept_b(&a);
^~
error: aborting due to 3 previous errors
...有效地提示我无法将特征对象移入框中。我是否必须先将值放入一个盒子中,然后再将该盒子放入特征盒中?
可变性规则不应该传递地确保我在 accept_b
中获得的特征是底层对象的唯一所有者,从而支持移动到盒子中吗?或者 Rust 没有记录必要的信息来提供那种精确度?我是否误解了 move 与 mutable borrow 语义?怎么回事?
最佳答案
Shouldn't the mutability rules transitively ensure that the trait I get in
accept_b
is the sole owner of the underlying object and thereby support movement into a box?
不,绝对不是。 accept_b
是借用引用,而不是拥有它。
可变性规则只会让你确定你是唯一借用该对象的人,但它不会给你所有权。
实际上永远不可能移出借用的内容并让引用闲置。如果你想移出一个 &mut
引用,你可以使用像 std::mem::replace(..)
这样的函数,但是它们需要你把另一个对象代替您要移出的对象,这又涉及复制实际内存数据,因此该类型必须是 Sized
。
所以不,如果 T
不是 Sized
,就不可能从 &mut T
中移出。
关于rust - 将可变特征对象引用移动到框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29621305/