-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
I've been talking about code reuse in Rust with my brother ( @emmetoneillpdx ) and one of the ideas we considered was a form of "static inheritance" which basically amounts to a syntax for automatically pulling either data or functions (or both) from existing structs and trait implementations. The proposed syntax is roughly based on Rusts' existing "Struct Update Syntax". Here's a simple pseudocode example:
trait Consume {
fn eat(&self);
fn drink();
}
struct Animal {
favorite_food : &'static str,
}
impl Consume for Animal {
fn eat(&self) {
println!("I'm eating some {}!", self.favorite_food);
}
fn drink() {
println!("I'm drinking now!");
}
}
struct Dog {
name : &'static str,
..Animal, // Statically "inherit" any field that is not already defined in Dog from Animal
}
impl
65F4
Consume for Dog {
fn drink() {
println!("I'm drinking out of a dog bowl!");
}
..Animal // Likewise, statically "inherit" any undefined Consume function implementation for Dog from Animal
// Since drink() has already been implemented for Dog, Animal's implementation won't be used.
}
//If Dog tries to inherit an implementation referring to a variable outside of its scope, compile error.
//Fundamentally the same as if you tried to copy + paste the eat(&self) implementation from Animal to Dog. (but without copy and pasting code!)
Allowing for code reuse this way should not fundamentally change the way Rust behaves at runtime but still allows for behavior that is somewhat similar to inheritance without error-prone code duplication practices. Essentially, we're just asking the compiler to copy/paste any undefined fields or functions from any known (at compile time) struct or implementation.
We don't have anything more concrete than that right now, but this is an idea that came up over the course of a conversation and we both wanted to share it and see what people thought. I'd love to hear feedback and form a discussion around this idea or others like it. Also, if you know of any relevant RFCs where it might be appropriate to share this (or is already working on a similar idea), please share.