繁体   English   中英

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

[英]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);
}

(游戏围栏链接)

...可以工作,但是它错误地显示为

<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

...有效地抱怨我无法将trait对象移动到盒子中。 必须把价值在一个盒子里然后再施放该箱成箱的-A-特质以后呢?

可变性规则是否应该通过传递性来确保我在accept_b获得的accept_b是基础对象的唯一所有者,从而支持移动到盒子中? 还是Rust不会记录必要的信息来提供这种美感? 我是否误解了举动与可变借用语义? 这是怎么回事?

可变性规则是否应该通过传递性来确保我在accept_b获得的accept_b是基础对象的唯一所有者,从而支持移动到盒子中?

不,绝对不是。 accept_b是借用引用,而不是引用。

可变性规则仅使您确定自己是唯一借用该对象的人,但它并未赋予您所有权。

实际上,永远不可能移出借用的内容并留下参考。 如果要移出&mut引用,可以使用std::mem::replace(..)类的函数,但它们需要您将另一个对象替换为移出的对象,这又会依次涉及复制实际的内存数据,因此类型必须为Sized

所以不,如果TSized &mut T ,则不可能移出&mut T

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM