Is it possible to extend a default method implementation of a trait in a struct?

后端 未结 3 888
孤独总比滥情好
孤独总比滥情好 2020-12-06 00:33

In traditional object-oriented languages (e.g. Java), it is possible to \"extend\" the functionality of a method in an inherited class by calling the original method from th

3条回答
  •  难免孤独
    2020-12-06 01:10

    Another way of accomplishing this would be to place the overriding method in impl block of struct

    trait A {
        fn a(&self) {
            println!("trait default method");
        }
    }
    
    struct B;
    
    impl B {
        fn a(&self) {
            println!("overridden method");
            // call default method here
            A::a(self);
        }
    }
    
    impl A for B {}
    
    fn main() {
        let a = B;
        a.a();
    } 
    

    playground

提交回复
热议问题