4 ms·
I think the article is wrong here. This is the code it says won't work: struct Base { ... } struct Derived: Base { foo: i32 } impl Derived {
by panic 7y ago
I think the article is wrong here. This is the code it says won't work:
struct Base { ... }
struct Derived: Base { foo: i32 }
impl Derived {
fn new() -> Derived {
Derived {
Base::new()..,
foo: 92,
}
}
}
You don't need to allocate memory progressively to support initializers like this. You could allocate the entire Derived struct, copy the return value of Base::new() into the beginning of the allocated struct, then initialize the rest of the fields. If you wanted to avoid the copy (and deal with complications like internal pointers), you could even make Base::new() write its return value directly into the Derived struct's memory (like C++'s "return value optimization" does).