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
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:
match s {
SomeStruct { ref a } if a == "Test" => {
println!("Match");
}
}
Thinking out of the box a bit, you can create a parallel type that has &str
instead of String
and add a method to convert between them:
struct SomeStruct {
a: String,
}
impl SomeStruct {
fn as_ref(&self) -> SomeStructRef {
SomeStructRef { a: &self.a }
}
}
struct SomeStructRef<'a> {
a: &'a str,
}
fn main() {
let s = SomeStruct {
a: "Test".to_string(),
};
match s.as_ref() {
SomeStructRef { a: "Test" } => {
println!("Match");
}
_ => panic!(),
}
}
You can then also create a constant for the value you'd like to match against:
#[derive(PartialEq, Eq)]
struct SomeStructRef<'a> {
a: &'a str,
}
const TEST_STRUCT: SomeStructRef = SomeStructRef { a: "Test" };
fn main() {
let s = SomeStruct {
a: "Test".to_string(),
};
match s.as_ref() {
TEST_STRUCT => {
println!("Match");
}
_ => panic!(),
}
}
There's nothing specific to structs here, the same concept works for enums:
enum SomeEnum {
One(String),
Two(String),
}
impl SomeEnum {
fn as_ref(&self) -> SomeEnumRef {
match self {
SomeEnum::One(v) => SomeEnumRef::One(v),
SomeEnum::Two(v) => SomeEnumRef::Two(v),
}
}
}
enum SomeEnumRef<'a> {
One(&'a str),
Two(&'a str),
}
fn main() {
let s = SomeEnum::Two("Test".to_string());
match s.as_ref() {
SomeEnumRef::Two("Test") => {
println!("Match");
}
_ => panic!(),
}
}