I have an enum:
enum Operation {
Add,
Subtract,
}
impl Operation {
fn from(s: &str) -> Result<Self, &str> {
match s {
"+" => Ok(Self::Add),
"-" => Ok(Self::Subtract),
_ => Err("Invalid operation"),
}
}
}
I want to ensure at compile time that every enum variant is handled in the from
function.
Why do I need this? For example, I might add a Product
operation and forget to handle this case in the from
function:
enum Operation {
// ...
Product,
}
impl Operation {
fn from(s: &str) -> Result<Self, &str> {
// No changes, I forgot to add a match arm for `Product`.
match s {
"+" => Ok(Self::Add),
"-" => Ok(Self::Subtract),
_ => Err("Invalid operation"),
}
}
}
Is it possible to guarantee that match expression returns every variant of an enum? If not, what is the best way to mimic this behaviour?