Is it possible to match against a String
in a struct in Rust with a static str
value? Here is a minimal example:
struct SomeStruct {
a: String,
}
fn main() {
let s = SomeStruct {
a: "Test".to_string(),
};
match s {
SomeStruct { a: "Test" } => {
println!("Match");
}
}
}
This won't compile because the static str
reference can't be matched against the String
member. Can it be made to work without destructuring a
and then adding a nested if statement in the match?
Thinking out of the box a bit, you can create a parallel type that has
&str
instead ofString
and add a method to convert between them:You can then also create a constant for the value you'd like to match against:
There's nothing specific to structs here, the same concept works for enums:
It is not currently possible to do this in a single pattern, though at some time it is likely to become possible. For now, it’s probably easiest to replace the pattern with a pattern and match guard, like this: