< 返回版块

wangbinyq 发表于 2019-11-14 09:19

如果有一个数据类型, 基本只会在堆上分配, 然后通过 Rc 引用, 那么 new 应该返回 Rc 还是 Self?

或者再加一个工厂方法返回 Rc, 有没有更好的 pattern 处理这种情况?

评论区

写评论
作者 wangbinyq 2019-11-14 09:46
struct Foo;

struct Bar { foo: Rc }

impl Foo { pub fn new () -> Self { Foo } }

// 因为 Foo 只在堆上分配, 所以直接返回 rc 还是上面这种比较好? 
impl Foo { pub fn new () -> Rc {  Rc  } }

impl Bar { pub fn new (foo: Rc) -> Self { Bar { foo } } }
jellybobbin 2019-11-14 09:38

这个一般都是返回self吧, 比如:

struct Foo {
    bar:Rc<String>
}


impl Foo{
    fn new()->Foo{
        Foo{
            bar:Rc::new(String::from("xxxx"))
        } 
    }
}
1 共 2 条评论, 1 页