I want to check whether a particular nested field is equal to a certain String
and only run the arm if it is. Something like the following:
struct Bar {
baz: usize,
value: Option<String>
}
struct Foo {
bar: Bar
}
let value = Foo { bar: Bar { baz: 1, value: Some("foobar".to_string()) } };
match value {
Foo {
bar: Bar {
baz,
value: Some("foobar") // does not work since &str != String
}
} => println!("Matched! baz: {}", baz),
_ => panic!("No Match")
}
Adding a match guard works but constant String
s aren't a thing so I can't guard using that, the only possibility I see is to guard against a new String
like so:
struct Bar {
value: Option<String>
}
struct Foo {
bar: Bar
}
let value = Foo { bar: Bar { value: Some("foobar".to_string()) } };
match value {
Foo {
bar: Bar { baz, value },
} if value == Some("foobar".to_string()) => println!("Matched! baz: {}", baz),
_ => panic!("No Match"),
}
Is this my only option or is there a better way?
Note: I have seen How to match a String against string literals? but my match is nested and more complicated (the above is only an example) so I can't just match against a reference to the String
.