【问题标题】:How to parameterize enumerator in rust?如何在rust中参数化枚举器?
【发布时间】:2020-07-23 00:04:29
【问题描述】:

我是 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

【问题讨论】:

  • 您能否举例说明为什么您实际上需要SourceType 枚举?一个常见的 Rust 习惯用法是只有 SourceProperties 并根据其变体确定类型。
  • 由于SourceType只有两个可能的值,你的hash map只能有零个、一个或两个元素,你想让这两个元素有两个固定的类型。对我来说,这听起来不像是地图,而更像是struct Sources { file: Option<FileProperties>, network: Option<NetworkProperties> }。如果您最多(或恰好)想要哈希映射中的一个元素,您可以简单地使用SourceProperties,如上一条评论中所述。
  • @eggyal 拥有一个单独的enum SourceType 的主要目的是应用程序将接受包含编码为String 值的SourceType 的用户请求("File",@ 987654341@)。所以我认为有一个单独的enum 是明智的,所以工作流程看起来像"File" -> SourceType::File -> FileProperties
  • @SvenMarnach 拥有enum SourceType 的原因是它是从用户输入中解码的。所以我认为定义这种类型是很自然的。更新了问题。

标签: enums rust type-safety


【解决方案1】:

您可以简单地使用散列集和封装属性的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);}
        }
    }
}

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 2015-12-03
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多