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!(),
}
}