具有默认特征实现的 Rust 泛型

问题描述 投票:0回答:1

我正在开发一个 Rust 项目,在该项目中我定义了几个特征(A1、A2 和 A3),每个特征都有多个实现。我还有一个 struct Algo,它采用基于这些特征的泛型。我想为泛型提供默认的特征实现,以防用户没有提供特定的实现。

这是我的代码:

pub trait A1 {
    fn test1();
}

#[derive(Default)]
pub struct Ex1_A1;

impl A1 for Ex1_A1 {
    fn test1() {
        println!("Ex1_A1");
    }
}

pub struct Ex2_A1;
impl A1 for Ex2_A1 {
    fn test1() {
        println!("Ex2_A1");
    }
}

pub trait A2 {
    fn test2();
}

pub struct Ex1_A2;
impl A2 for Ex1_A2 {
    fn test2() {
        println!("Ex1_A2");
    }
}

pub trait A3 {
    fn test3();
}

pub struct Ex1_A3;
impl A3 for Ex1_A3 {
    fn test3() {
        println!("Ex1_A3");
    }
}

struct Algo<B: A1, S: A2, M: A3> {
    a1: B,
    a2: S,
    a3: M
} 

impl <B: A1, S: A2, M: A3> Algo<B, S, M> {
    pub fn new(bbs: Option<B>, su: Option<S>, mac: Option<M>) -> Self {
        let bbs = bbs.unwrap_or(Ex1_A1);
        let su = su.unwrap_or(Ex1_A2);
        let mac = mac.unwrap_or(Ex1_A3);
        Self {
            a1: bbs,
            a2: su,
            a3: mac,
        }
    }
}

我的问题是,如何为 Algo 结构中的泛型 B、S 和 M 提供默认实现?我尝试过使用 Option 和 unwrap_or,但它似乎没有按预期工作。

如果有任何关于如何在 Rust 中有效处理这种情况的指导或示例,我将不胜感激。

谢谢!

generics rust traits
1个回答
0
投票

编译时值(泛型参数的类型)不能依赖于运行时值 (

Option
)。所以你不能这样做。

© www.soinside.com 2019 - 2024. All rights reserved.