I am looking for a way to see if a variable is of a specific variant of an enum, without specifying all variants in the type. Something like the following (this does not work)
enum Sample {
Var1 {data: i32},
Var2 {data1: i32, data2: i32},
Var3 {data1: f32, data2:f32},
Var4,
}
fn is_of_var(val: Sample, variant: ???) -> bool {
match val {
variant => true,
_ => false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let s = Sample::Var2{data1: 1, data2: 2};
let is_var2 = is_of_var(s, Sample::Var2);
let is_var1 = is_of_var(s, Sample::Var1);
assert!(is_var2);
assert!(!is_var1);
}
}
Preferably, I can write is_of_var as a macro that will work with any enum. Any ideas on how to accomplish this task? I just need to know if the variable is of that enum variant, not what its values are
Alternatively, you could have a C-like enumeration which shadows your data-holding enumeration (ala this strum crate macro) and compare discriminant(s.into()) and discriminant(CLikeEnum::Name).
Ahh, sorry, I didn't fully understand what you were looking for. My thinking was that instead of using functions/methods like is_var1, is_var2, etc. (or some kind of parametric is_of_var) you could replace if with if let (or while with while let) at the call site, so there's no function involved at all. But if you specifically need this as a function or macro then the approaches in @quinedot's answer will be of more help.