我想为以下结构编写初始化程序。
struct Foo {
bar: &Bar
}
推荐使用&T
在 Box<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/