如何将可变特征对象引用移动到框中?我也许会期待
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);
}
Run Code Online (Sandbox Code Playgroud)
...工作,但它出错了
<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
Run Code Online (Sandbox Code Playgroud)
...有效地抱怨我无法将特质物体移动到盒子里.我是否必须先将值放在一个框中,然后将该框放入一个特征框中?
可变性规则不应该过渡性地确保我所获得的特征accept_b
是底层对象的唯一所有者,从而支持移动到框中吗?或者Rust没有记录提供这种精确性的必要信息吗?我是否误解了可变借用语义?这是怎么回事?
可变性规则不应该过渡性地确保我所获得的特征
accept_b
是底层对象的唯一所有者,从而支持移动到框中吗?
不,绝对不是.accept_b
是借用参考,而不是拥有它.
可变性规则只会让您确定您是唯一借用该对象的人,但它并不能为您提供所有权.
实际上,永远不可能摆脱借来的内容并留下参考资料.如果你想要移出一个&mut
引用,你可以使用像这样的函数std::mem::replace(..)
,但它们要求你把另一个对象放在你要移出的对象的位置,这反过来又涉及复制实际的内存数据,因此类型必须是Sized
.
所以,不,这是不可能迁出的&mut T
,如果T
是没有Sized
.
归档时间: |
|
查看次数: |
1147 次 |
最近记录: |