initialization - 如何初始化包含引用的结构?

标签 initialization rust lifetime

我想为以下结构编写初始化程序。

struct Foo {
    bar: &Bar
}

推荐使用&TBox<T>为了灵 active ,这就是我在这里想要的。如果没有初始化程序,您将使用这样的结构。

{
    let bar = ...;
    let foo = Foo { bar: bar };

    // use foo    

    // dealloc bar and foo
}

这行得通。但是我想分配 &Bar在初始化程序中。现在显然分配 bar在堆栈上将不起作用,因为一旦初始化程序返回,它就会超出范围。所以我想我可以使用 Box .

fn new() -> Foo {
    let bar = Box::new(...);
    Foo { bar: &*bar }
}

这也不起作用,因为我猜我们只是借用值(value)而不是转移所有权,这仍然会释放 bar一次new返回。

我是否被迫使用 Box在这种情况下的结构中?

编辑

注意:需要引用的原因是因为 Bar在我的例子中实际上是一个通用特征,因此大小可能会有所不同,这意味着堆栈上的分配将不起作用。

最佳答案

你的问题没有意义。如果您在 new 方法中构造对象,那么根据定义您知道类型是什么(因为您正在调用该构造函数),并且您不需要将其视为特征对象。你应该只使用类型!

The reason the reference is needed is because Bar is actually a generic trait in my case and thus the size can vary which means allocation on the stack won't work.

这不完全正确!如果你想接受一个参数,并且你想转移所有权,那么你可以简单地将类型限制为你想要的特征:

trait Talker { fn talk(&self); }

struct Dog;
impl Talker for Dog { fn talk(&self) { println!("Woof") }}

struct Cat;
impl Talker for Cat { fn talk(&self) { println!("Meow") }}

struct OwnAGeneric<T: Talker> {
    t: T
}

impl<T: Talker> OwnAGeneric<T> {
    fn new(t: T) -> OwnAGeneric<T> { OwnAGeneric { t: t } }

    fn talk(&self) { println!("I own this:"); self.t.talk(); }
}

fn main() {
    let owned_cat = OwnAGeneric::new(Cat);  
    owned_cat.talk();
}

这应该由编译器单态化,并且基本上和您手动编写代码一样快。这也允许在堆栈上分配所有内容。

关于initialization - 如何初始化包含引用的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28525270/

相关文章:

rust - TryFromIntError 用法

rust - 由于需求冲突,无法为生命周期参数 `' de` 推断出合适的生命周期

rust - 摆弄生命周期 : sanity check on unsafe reinterpretation of lifetimes

c - 从另一个函数调用构造函数时的存储持续时间

java - 初始化子类字段

ios - XIB 需要初始化器——没有 Storyboard

iOS 6 - 何时实例化(创建类的对象)何时不实例化?

rust - PI常数不明确

rust - 如何在 vec 中存储结构引用并稍后在其他地方使用该结构?

java - 如何从Java中的列表初始化变量?