簡體   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