如何在 Rust 中参数化枚举器?
How to parameterize enumerator in rust?
我是 Rust 的新手,遇到了以下简单问题
我有以下 2 个枚举:
enum SourceType{
File,
Network
}
enum SourceProperties{
FileProperties {
file_path: String
},
NetworkProperties {
ip: String
}
}
现在我想要 HashMap<SourceType, SourceProperties>
,但在这样的实现中,可能会有映射 File -> NetworkProperties
,这不是预期的。
我正在考虑以某种方式将 enum SourceProperties<T>
参数化为 SourceType
,但似乎不可能。有没有办法提供这种类型安全保证?
UPD: enum SourceType
的目的是实际的 SourceType
是用户输入,将被解码为 String
值("File"
、"Network"
)。所以工作流程看起来像这样
"File" -> SourceType::File -> SourceProperties::NetworkProperties
您可以简单地使用哈希集和封装属性的 enum
,以便稍后匹配它们:
use std::collections::HashSet;
#[derive(PartialEq, Eq, Hash)]
struct FileProperties {
file_path: String
}
#[derive(PartialEq, Eq, Hash)]
struct NetworkProperties {
ip: String
}
#[derive(PartialEq, Eq, Hash)]
enum Source {
File(FileProperties),
Network(NetworkProperties)
}
fn main() {
let mut set : HashSet<Source> = HashSet::new();
set.insert(Source::File(FileProperties{file_path: "foo.bar".to_string()}));
for e in set {
match e {
Source::File(properties) => { println!("{}", properties.file_path);}
Source::Network(properties) => { println!("{}", properties.ip);}
}
}
}
我是 Rust 的新手,遇到了以下简单问题
我有以下 2 个枚举:
enum SourceType{
File,
Network
}
enum SourceProperties{
FileProperties {
file_path: String
},
NetworkProperties {
ip: String
}
}
现在我想要 HashMap<SourceType, SourceProperties>
,但在这样的实现中,可能会有映射 File -> NetworkProperties
,这不是预期的。
我正在考虑以某种方式将 enum SourceProperties<T>
参数化为 SourceType
,但似乎不可能。有没有办法提供这种类型安全保证?
UPD: enum SourceType
的目的是实际的 SourceType
是用户输入,将被解码为 String
值("File"
、"Network"
)。所以工作流程看起来像这样
"File" -> SourceType::File -> SourceProperties::NetworkProperties
您可以简单地使用哈希集和封装属性的 enum
,以便稍后匹配它们:
use std::collections::HashSet;
#[derive(PartialEq, Eq, Hash)]
struct FileProperties {
file_path: String
}
#[derive(PartialEq, Eq, Hash)]
struct NetworkProperties {
ip: String
}
#[derive(PartialEq, Eq, Hash)]
enum Source {
File(FileProperties),
Network(NetworkProperties)
}
fn main() {
let mut set : HashSet<Source> = HashSet::new();
set.insert(Source::File(FileProperties{file_path: "foo.bar".to_string()}));
for e in set {
match e {
Source::File(properties) => { println!("{}", properties.file_path);}
Source::Network(properties) => { println!("{}", properties.ip);}
}
}
}