How can I use the default implementation of a trait method instead of the type's custom implementation?

[亡魂溺海] 提交于 2019-12-01 15:57:54

问题


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?
}

回答1:


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());
}


来源:https://stackoverflow.com/questions/26364744/how-can-i-use-the-default-implementation-of-a-trait-method-instead-of-the-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!