In your code, when providing a default implementation for `inflate_by`, you are invoking the trait (hence "virtual") method `get_radius`. If the compiler compiles `inflate_by` when seeing just the `Inflate` source code, then this must be translated to an indirect call through the vtable.
The point of anonymous members (and, to a greater extent, of the single inheritance) is to ensure that access to data members is just that, without any function calls. To achieve that with the approach you described, the compiler will need to re-compile `inflate_by` for each and every struct that implements it; only then it would be able to inline `get_radius`. Is this what the Rust compiler does today? I have no specific knowledge of the answer, but the simplest thing for the compiler would be to keep `get_radius` as a virtual function call. Doing otherwise would require quite a bit of machinery (e.g., what if `Inflate` is defined in another crate, and all we have is its fully-compiled shared object file? There would need to be some "extra stuff" available to the compiler to do this re-compilation, as the source is not available at that point). Therefore I suspect that this approach would suffer from significant performance issues. On 2013-11-15, at 2:09, Tommi <[email protected]> wrote: > > trait Inflate { > fn get_radius<'s>(&'s mut self) -> &'s mut int; > > fn inflate_by(&mut self, amount: int) { > *self.get_radius() += amount; > } > } > > trait Flatten { > fn get_radius<'s>(&'s mut self) -> &'s mut int; > > fn release_all_air(&mut self) { > *self.get_radius() = 0; > } > } > > struct Balloon { > radius: int > } > > impl Inflate for Balloon { > fn get_radius<'s>(&'s mut self) -> &'s mut int { > &mut self.radius > } > } > > impl Flatten for Balloon { > fn get_radius<'s>(&'s mut self) -> &'s mut int { > &mut self.radius > } > } > >
_______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
