Put A Function In A Rust Enum
This is a shift in my thinking. I'm making an emum that contains structs that I can then call methods on after matching them.
Took me a while to get my head around this pattern but I really like it.
(Previously, I'd been making a stuct with a field that contained the enum which still is a solid play in some cases, but for this case I like this better)
#[derive(Debug)]
pub struct KeyValueParam {
key: String,
value: String,
}
impl KeyValueParam {
pub fn line(&self) -> String {
format!("{}: {}", &self.key, &self.value)
}
}
#[derive(Debug)]
pub enum Param {
KeyValue(KeyValueParam)
}
fn main() {
let p = Param::KeyValue(KeyValueParam{
key: "alfa".to_string(),
value: "bravo".to_string()
});
let output = match p {
Param::KeyValue(kvp) => kvp.line()
};
println!("{}", output);
}
Output:
alfa: bravo
-- end of line --