Hello, this is a real old topic, and i want to talk about it again. I’m sure you’ve read RFC349 and RFC1546 on this topic, which both exhibits some real powerful way as a feature - too powerful that they’re repeatly postponing. So I’d like to try something different: a minimalist approach.
First i’ll assume that we want to build this feature as a library, maybe implemented using proc macros. This gives some flexibility for community experiment. And all we want to talk about is what support we want from the language side.
Then let’s see what we want to get. Something in par with single inheritance in C++ is quite enough. Multiple inheritance is undesirable since it will bring up the diamond inheritance problem. So what’s essential behind single inheritance. It’s just a reusable sub-object of the base class in the struct instance supporting cheap casting between the two. Putting the delegation issue aside, and that’s all.
So what we can expect from the language is: an field attribute that tells Layout to put this field just at the beginning of the memory segment of the value. (offset_of == 0) It can only occur once in a struct. Something like this:
struct Foo {
#[zero_offset]
pub base: Bar,
}
And that’s (almost) all ! The compiler should ensure that it is defined behavior to cast &Foo to &Bar. It should also ensure vice versa if the Bar is actually living as a base field. So such transmutation methods can be provided by a library.
I said almost because actually there’s another issue in it: ZST issue. If Bar is ZST and Foo is not, you can’t always cast Bar back. This can be resolved by special rules and hacks, i believe. But i know too little to talk about them.
With such support. I believe people can just write a proc macro to do whatever structural reuse they want.
What do you think?