首页 文章

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

提问于
浏览
2

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

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没有记录提供这种精确性的必要信息吗?我是否误解了可变借用语义?这是怎么回事?

1 回答

  • 6

    不应该通过可变性规则传递确保我在accept_b中获得的特征是底层对象的唯一所有者,从而支持移动到框中吗?

    不,绝对不是 . accept_b 正在借用参考资料,而不是拥有它 .

    可变性规则只会让您确定您是唯一借用该对象的人,但它不会给您所有权 .

    实际上,永远不可能摆脱借来的内容并留下参考资料 . 如果你想移出一个 &mut 引用,你可以使用像 std::mem::replace(..) 这样的函数,但是它们要求你用另一个对象来代替你要移出的对象,这反过来又涉及复制实际的内存数据,从而类型必须是 Sized .

    所以不,如果 T 不是 Sized ,就不可能退出 &mut T .

相关问题