【问题标题】:How to use traits implemented for some of the types embedded in an enum's variants?如何使用为枚举变体中嵌入的某些类型实现的特征?
【发布时间】:2021-08-11 16:56:22
【问题描述】:

我有一个包含大约 20 个变体的枚举。由于无法为枚举的变体实现特征(请参阅Can traits be used on enum types?How do I implement a trait for an enum and its respective variants?),我已经为嵌入在变体中的一些类型实现了我的特征。

给定一个类型为枚举的变量,访问该特征的惯用/最佳方式是什么?由于我需要在不同的地方使用它,我尝试将代码移动到一个函数中,然后我的以下尝试返回一个Option<Box<&dyn Trait>>

pub struct X { pub name: String, pub weight: u32 }
pub struct Y { pub name: String }
pub struct Z {}

pub enum Node {
    X(X),
    Y(Y),
    Z(Z),
}

pub trait Weighted {
    fn weight(&self) -> u32;
}

impl Weighted for X {
    fn weight(&self) -> u32 { return self.weight; }
}

impl Weighted for Z {
    fn weight(&self) -> u32 { return 3; }
}

pub fn as_weighted_node(node: &Node) -> Option<Box<&dyn Weighted>> {
    match node {
        Node::X(x) => Some(Box::new(x)),
        Node::Z(z) => Some(Box::new(z)),
        _ => None
    }
}

let node: Node = Node::X(X { name: "x1".to_string(), weight: 1 });

println!("{}", as_weighted_node(&node).unwrap().weight());

【问题讨论】:

  • 您的代码有效,因此您的问题似乎有了答案——太好了!您应该将其作为答案发布,而不是对您的问题进行编辑,然后可能会接受该答案。这样一来,问题就会在搜索结果中显示为已解决,人们可以对您的答案进行投票或提供替代答案,您的解决方案可以对未来遇到相同问题的人更有帮助。

标签: rust


【解决方案1】:

看来Box是不需要的,as_weighted_node可以写成:

pub fn as_weighted_node(node: &Node) -> Option<&dyn Weighted> {
    match node {
        Node::X(x) => Some(x),
        Node::Z(z) => Some(z),
        _ => None
    }
}

我仍然不确定这是处理此问题的最佳方法。

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多