Suggestion for making Rust's trait system more usable for generics

For future readers, these threads may also be helpful: Inheritance, why is bad? and How to implement inheritance-like feature for Rust?

From my point of view (coming from Java) who likes Rust enough to write a book Rust for Java Developers, Rust already has the sort of inheritance I would use in Java.

For data types you can do:

struct A { 
//...
}

struct B {
   a: A,
//...
}

and get all the relevant fields. This is sometimes combined with Deref, to unwrap an inner object.
But that's not common even in Java. Usually in Java, I would have one interface extend another, which you can do with Traits:

trait FooBar : Foo {
//...
}

Traits can also provide a default method just as interfaces do in Java. I would usually use this to implement one method in terms of the others in the interface, that way all the impls get it for free.
(Copied from Rust by example)

trait Animal {
    // Instance method signatures; these will return a string.
    fn name(&self) -> &'static str;
    fn noise(&self) -> &'static str;

    // Traits can provide default method definitions.
    fn talk(&self) {
        println!("{} says {}", self.name(), self.noise());
    }
}

This can be made even more powerful using Associated types.

However the real power comes when define traits in terms of other traits:

trait Foo {
   // Some methods I expect others to implement...
}

trait FooExt {
   // Methods I am going to implement...
}

impl<T> FooExt for T where T:Foo {
    // Implementation...
}

This way anyone can implement the Foo trait for whatever structure they want, and they will automatically get the implementation of FooExt on their object. This is a very powerful feature that replaces many of the usecases where you might use an abstract class in Java, but it goes further than that because it doesn't force a "child" to have only one "parent". Additionally it allows for much more powerful overloading, where Java Overloads functions based on the function signature, Rust does so based on the Trait, so you don't have to worry about collisions.

The book I'm putting together has some additional details, but it is very far form finished. If anyone is interested in helping out, let me know.

3 Likes