如何使用 trait 方法的默认实现而不是类型的自定义实现? [英] How can I use the default implementation of a trait method instead of the type's custom implementation?

查看:36
本文介绍了如何使用 trait 方法的默认实现而不是类型的自定义实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些 trait 方法有默认实现,可以被实现者覆盖.如何为覆盖默认值的结构使用默认实现?

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?

例如:

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

推荐答案

我想出的一个解决方案是定义一个包含我想要更改的结构的虚拟结构.然后,我可以挑选要覆盖的方法以及要保留为默认值的方法.

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.

扩展原始示例:

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

这篇关于如何使用 trait 方法的默认实现而不是类型的自定义实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆