I have come up with 3 ways to model a system I am working on:
// 1. using a HashMap with actual types;
// Pros: fast to look up/delete items
// Cons: hard to understand what the types represent
pub struct CamerasConfig(HashMap<usize, (String, Option<process::Child>)>);
// 2. still using a HashMap, but using type aliases instead of primitive types to improve readability
// Pros: same as above
// Cons: not sure if this is a convention (using type aliases in such a way)
type Port = usize;
type Command = String;
type VideocaptureProcess = Option<process::Child>;
pub struct CamerasConfig(HashMap<Port, (Command, VideocaptureProcess)>);
// 3: just using a vector of structs
// Pros: probably the most readable
// Cons: must implement a check when parsing that filters out duplicates; doesn't convey that the port is basically the Key and the are values
pub struct CamerasConfig(Vec<CameraConfig>);
struct CameraConfig {
port: usize,
command: String,
videocapture_process: Option<process::Child>,
}
Clearly the items don't need to be ordered (otherwise a hashmap wouldn't work in the first place), but I do need to prevent duplicate ports (the ports are unique identifiers for each camera), which is why I initially tended towards a simple hashmap. However, now that I am adding some more attributes to each camera, I think it is starting to get less readable. Any ideas? Maybe a HashSet would also work, but would I have to implement Eq and Hash myself then (if I still want port to be the unique identifier)? Are there any conventions/best practices for this problem?
Ok, I like that solution, I thought about that as well. So basically accepting a slight overhead of one integer (by storing the port twice), in favor of readability. If I really need to cut down on the memory footprint (I don't think I'll have to), then I could always just remove port from CameraConfig.
I'd move the pattern match inside the closure body, because to my taste, that pattern in the closure argument is just too complex. Also, you can just use the port from the structure and drop the key entirely: