2

我对 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
4

1 回答 1

3

您可以简单地使用散列集和enum封装属性的 an,以便稍后匹配它们:

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);}
        }
    }
}

操场

于 2020-07-23T11:13:37.413 回答