将可变特征对象引用移动到框中

Moving a mutable trait object reference into a box

如何将可变特征对象引用移动到框中?例如我可能会期待

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);
}

(playpen link)

... 可以工作,但它会出错

<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