gpt4 book ai didi

rust - Rust将枚举返回为通用类型

转载 作者:行者123 更新时间:2023-12-03 11:38:47 24 4
gpt4 key购买 nike

我正在尝试创建一个包含节点集合的结构。为了限制类型,这些节点中的每个节点都可以保留枚举类型NodeVal的值。
然后,我可以将访问器函数添加到Container结构中,以获取和设置值。但是,我没有添加get_node_f64, get_node_i64等,而是尝试创建一个通用类型的函数,该函数接受实现Num trait的类型。
这似乎不起作用,因为Node的val属性是NodeVal而不是T。但是,如果将其设为T,它将可以是任何类型,我想避免这种类型。
有什么方法可以实现我想做的,还是我在构造错误的方法呢?

use std::collections::HashMap;
use num_traits::Num;

pub enum NodeVal {
Str(String),
F64(f64),
Uint64(u64),
Int64(i64),
}

pub struct Node {
id: i32,
val: NodeVal
}

pub struct Container {
nodes: HashMap<i32, Node>
}

impl Container {
pub fn new() -> Self {
Container {
nodes: HashMap::new()
}
}

pub fn get_node_str(&self, key: &i32) -> Option<String> {
match self.nodes.get(key) {
Some(r) => match &r.val {
NodeVal::Str(x) => Some(x.to_string()),
_ => None
},
None => None
}
}

// Does not compile
pub fn get_node_num<T: num_traits::Num>(&self, key: &i32) -> Option<T> {
match self.nodes.get(key) {
Some(r) => match &r.val {
NodeVal::F64(x) | NodeVal::Uint64(x) | NodeVal::Int64(x) => Some(*x),
_ => None
},
None => None
}
}
}

最佳答案

This does not work seemingly because the val property of Node is NodeVal rather than T. However if I make it T it will be able to be any type, which I want to avoid.


我得到的是,它不起作用,因为 x在您要匹配的三个变体中具有不同的类型,这对Rust毫无意义,它提示 x中的 F64f64,即 xUint64,而 u64中的 xInt64,因此* i64的类型没有意义。
您对特征范围的使用也不正确,特征范围是调用者指定类型的一种方法,但是 x不会在一秒钟内就考虑到这一点。
再加上推理是没有道理的:

However if I make it T it will be able to be any type, which I want to avoid.

get_node_num决定返回类型是什么, get_node_num完全没用。 T也无法工作,因为您不能在Rust中返回“f64或u64或i64”,除非创建一个新的 get_node_num来存储这些替代项。

关于rust - Rust将枚举返回为通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64479238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com