【问题标题】:Function return type overloading in TraitTrait 中的函数返回类型重载
【发布时间】:2022-01-14 01:32:20
【问题描述】:

我正在编写一个输出标量 T 或 NdArray ArrayBase<ViewRepr<&T>, I> 的 trait 函数。我知道 Rust 不支持函数重载。我遇到过不同的解决方案,例如输出元组(第一个元素是标量,第二个元素是数组)。你觉得这个解决方案在 Rust 中是惯用的吗?或者您知道更好的解决方法吗?

我目前的解决方案是创建两个不同的特征,一个实现一个输出标量的函数,另一个在另一个特征中输出一个数组的函数。

我正在寻找更好的解决方案,因为它可以显着减轻我的代码库。

【问题讨论】:

    标签: rust overloading


    【解决方案1】:

    您可以在输出的 trait 中使用 associated type

    pub trait MyTrait {
        type Output;
    
        fn execute(&self) -> Self::Output;
    }
    
    ...
    struct MyCompute;
    
    impl MyTrait for MyCompute {
        type Output = u64;
    
        fn compute(&self) -> Self::Output { ... }
    }
    

    【讨论】:

    • 这是我需要的 100%。非常感谢您的帮助。
    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 2021-02-01
    • 2022-01-13
    • 2013-07-29
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多