繁体   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