I am using Rust 1.15.1 and, recently, I stumbled over a problem I could not find a straight forward solution for.
When you look at examples using pattern matching they usually destructure the object in the match expression and continue to work with members within that object. However, I'd like to NOT destructure it, but only match against it and dispatch the complete object (using move semantics) to one of several other functions depending on its properties.
The following code works and does exactly what I need. However, I need to introduce an "artificial" enum type and a second match expression. I wonder if there is a more straight forward and simpler solution?
#[derive(Debug)]
enum Number {
Constant { value: i32 },
}
fn process_even(n: Number) {
println!("even: {:?}", n);
}
fn process_odd(n: Number) {
println!("odd: {:?}", n);
}
fn process(n: Number) {
enum Action {
ProcessEven,
ProcessOdd,
}
let action = match n {
Number::Constant { value: c, .. } if 0 == c % 2 => Action::ProcessEven,
_ => Action::ProcessOdd,
};
match action {
Action::ProcessEven => process_even(n),
Action::ProcessOdd => process_odd(n),
}
}
fn main() {
process(Number::Constant { value: 4711 });
process(Number::Constant { value: 2000 });
}
Copy
as value. What you suggested is exactly what I had in mind and actually tired to do. However, as you already mentioned, this seems to only work with members that implementCopy
trait. Using a 'bool' works in the special case of two alternatives, but one would make use of the same mechanism. Using function pointers might be the simple solution I am looking for. I'll try, thanks :-) – Jonny Dee Mar 12 '17 at 03:51