Search code examples
enumsrusttype-safety

How to parameterize enumerator in rust?


I'm very new to Rust and faced the following simple problem

I have the following 2 enums:

enum SourceType{
   File,
   Network
}

enum SourceProperties{
   FileProperties {
       file_path: String
   },
   NetworkProperties {
        ip: String
   }
}

Now I'd like to have HashMap<SourceType, SourceProperties>, but in such an implementation there is a potential to have mapping File -> NetworkProperties which is not what's expected.

I was thinking about to parameterize enum SourceProperties<T> with SourceType somehow, but it does not seem to be possible. Is there a way to provide such typesafety guarantees?

UPD: The intention of having the enum SourceType is that the actual SourceType is a user input which will be decoded as a String value ("File", "Network"). So the workflow would look like this

"File" -> SourceType::File -> SourceProperties::NetworkProperties

Solution

  • You can simple use a hash set and an enum that encapsulates the properties, for latter matching of them:

    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