How can I use the default implementation of a trai

2019-02-21 20:14发布

Some trait methods have default implementations which can be overwritten by an implementer. How can I use the default implementation for a struct that overwrites the default?

For example:

trait SomeTrait {
    fn get_num(&self) -> i32;
    fn add_to_num(&self) -> i32 {
        self.get_num() + 1
    }
}

struct SomeStruct;
impl SomeTrait for SomeStruct {
    fn get_num(&self) -> i32 {
        3
    }
    fn add_to_num(&self) -> i32 {
        self.get_num() + 2
    }
}

fn main() {
    let the_struct = SomeStruct;
    println!("{}", the_struct.add_to_num()); // how can I get this to print 4 instead of 5?
}

标签: rust traits
1条回答
该账号已被封号
2楼-- · 2019-02-21 20:22

One solution I've come up with is to define a dummy struct that contains the struct I want to change. I can then cherry-pick which methods I want to overwrite and which ones I want to keep as the default.

To extend the original example:

trait SomeTrait {
    fn get_num(&self) -> i32;
    fn add_to_num(&self) -> i32 {
        self.get_num() + 1
    }
}

struct SomeStruct;

impl SomeTrait for SomeStruct {
    fn get_num(&self) -> i32 {
        3
    }
    fn add_to_num(&self) -> i32 {
        self.get_num() + 2
    }
}

fn main() {
    struct SomeOtherStruct {
        base: SomeStruct,
    }

    impl SomeTrait for SomeOtherStruct {
        fn get_num(&self) -> i32 {
            self.base.get_num()
        }
        //This dummy struct keeps the default behavior of add_to_num()
    }

    let the_struct = SomeStruct;
    println!("{}", the_struct.add_to_num());

    //now we can call the default method using the original struct's data.
    println!("{}", SomeOtherStruct { base: the_struct }.add_to_num());
}
查看更多
登录 后发表回答