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

标签 rust

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

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 中移出。

关于rust - 将可变特征对象引用移动到框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29621305/

相关文章:

algorithm - 有没有更好的方法来使用图像 0.18 crate 实现中点圆算法?

macros - 我可以通过宏中的多个规则重复匹配吗?

rust - 向向量添加临时值时的生命周期

java - Android NDK : Two prebuilt shared libraries, 但其中一个依赖于另一个

pointers - 将成对数组传递给函数时,未为类型 `&A` 实现特征

rust - 从 SliceStorage 和 SliceStorageMut 中提取原始切片

rust - Rocket CORS如何使用Request Guard返回字符串?

generics - 如何在执行动态调度的 Rust 中实现泛型函数?

rust - 如何使用 Rust 跟踪获取/存储跨度持续时间?

rust:借用的值必须在静态生命周期内有效