Yes, you can simplify the match expression using the From or Into traits, or by leveraging the yaml-rust library's From implementations for basic types. However, in this case, since PrefValue is a custom enum and Yaml is from the yaml-rust crate, you can use the Into trait if PrefValue implements it for Yaml.
But looking at the provided links and the code, there is no direct From or Into implementation between PrefValue and Yaml in the mozprofile or yaml-rust crates. Therefore, the simplest way to achieve this is to use a map operation or a helper function to convert PrefValue to Yaml.
If you frequently convert PrefValue to Yaml, you can define a helper function or a trait implementation:
rustimpl From<PrefValue> for Yaml { fn from(value: PrefValue) -> Self { match value { PrefValue::Bool(b) => Yaml::Boolean(b), PrefValue::Int(i) => Yaml::Integer(i), PrefValue::String(s) => Yaml::String(s), } } }
Now, you can use it like this:
rustlet yaml_value: Yaml = pref_value.into(); // or let yaml_value = Yaml::from(pref_value);
If you want to avoid writing a match block every time, you could also use a macro:
rustmacro_rules! to_yaml { ($value:expr) => { match $value { PrefValue::Bool(b) => Yaml::Boolean(b), PrefValue::Int(i) => Yaml::Integer(i), PrefValue::String(s) => Yaml::String(s), } }; } let yaml_value = to_yaml!(pref_value);
If you can modify the PrefValue enum, you could add a method to it:
rustimpl PrefValue { fn to_yaml(&self) -> Yaml { match self { PrefValue::Bool(b) => Yaml::Boolean(*b), PrefValue::Int(i) => Yaml::Integer(*i), PrefValue::String(s) => Yaml::String(s.clone()), } } } let yaml_value = pref_value.to_yaml();
From/Into if you want idiomatic Rust and plan to use this conversion often.PrefValue enum.PrefValue enum and want a clean, object-oriented approach.Vibe can make mistakes. Check answers. Learn more