簡體   English   中英

Rc,RefCell和Box組合的新類型模式

[英]Newtype pattern of the combinations of Rc, RefCell and Box

因為我不想一次又一次鍵入Rc::new(RefCell::new(Box::new(MyType::new(args...)))) ,所以我決定創建新類型的RcRefBox如下所示:

use std::rc::Rc;
use std::cell::RefCell;

struct RcRefBox<T>(Rc<RefCell<Box<T>>>);

impl<T> RcRefBox<T> {
    fn new(value: Box<T>) -> RcRefBox<T> {
        RcRefBox(Rc::new(RefCell::new(value)))
    }
}

trait Interface {}

struct A;
impl Interface for A {}

fn main() {
    let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
}

該代碼無法與以下錯誤一起編譯:(游戲圍欄: http : //is.gd/ITiR8Q

<anon>:19:16: 19:35 error: the trait `core::marker::Sized` is not implemented for the type `Interface` [E0277]
<anon>:19     let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
                         ^~~~~~~~~~~~~~~~~~~
<anon>:19:16: 19:35 note: `Interface` does not have a constant size known at compile-time
<anon>:19     let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
                     ^~~~~~~~~~~~~~~~~~~
<anon>:19:38: 19:51 error: the trait `core::marker::Sized` is not implemented for the type `Interface` [E0277]
<anon>:19     let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
                                               ^~~~~~~~~~~~~
<anon>:19:38: 19:51 note: `Interface` does not have a constant size known at compile-time
<anon>:19     let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
                                               ^~~~~~~~~~~~~
error: aborting due to 2 previous errors

我該如何解決這些錯誤?

問題不僅僅在於struct本身,而在於您通過的trait

特性對象是動態調整大小的對象(不實現Sized )。

通常,當您在泛型類型(此處為T )上指定邊界時,會對其進行約束,但是在引入Sized時,由於大多數泛型代碼僅處理Sized類型和結果T ,因此決定將其用作默認邊界。表示T: Sized

有一個特殊的“加寬”字樣必然表示“ T可能未調整Sized ”: ?Sized ,如果您希望能夠獲取trait對象,則必須應用。 將其添加到您的代碼中:

use std::rc::Rc;
use std::cell::RefCell;

struct RcRefBox<T: ?Sized>(Rc<RefCell<Box<T>>>);  // ?Sized

impl<T: ?Sized> RcRefBox<T> {                     // ?Sized
    fn new(value: Box<T>) -> RcRefBox<T> {
        RcRefBox(Rc::new(RefCell::new(value)))
    }
}

trait Interface {}

struct A;
impl Interface for A {}

fn main() {
    let iface: RcRefBox<Interface> = RcRefBox::new(Box::new(A));
}

使它起作用( http://is.gd/pSZKK2 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM