Search code examples
rusttraits

Is it possible to declare a trait that accepts more methods that the ones declared in its body?


Something like:

pub trait MyTrait {
    // No methods defined/declared
}

impl MyTrait for MyType {
    fn method_one_not_declared_neither_defined(&self) {
        // body of trait method impl here
    }

    fn method_two_not_declared_neither_defined(&self) {
        // body of trait method impl here
    }
}

Solution

  • While the trait itself cannot be extended, you can still add behaviour to all types which implement a trait. This can be done using extension traits and blanket implementations.

    trait MyTrait {}
    
    struct MyType;
    
    impl MyTrait for MyType {}
    
    trait TraitExt {
        fn foo(&self) {
            println!("Foo");
        }
    }
    
    impl<T> TraitExt for T where T: MyTrait {}
    
    fn main() {
        let t = MyType {};
        t.foo();
    }
    

    Playground

    This is not the same as extending MyTrait however - TraitExt must be in scope for foo to be called.