I can straight-forwardly match a String
in Rust:
let a = \"hello\".to_string();
match &a[..] {
\"hello\" => {
println!(\"Mat
It's a known limitation of Rust's patterns.
Method calls (including internal methods for operators like ==
) automatically call .deref()
as needed, so String
gets automagically turned into &str
for comparisons with literals.
On the other hand, the patterns are quite literal in their comparisons, and find that String
and &str
are different.
There are two solutions:
Change Option
to Option<&str>
before matching on it: Some(a).as_ref().map(String::as_str)
. The as_ref()
makes Option<&String>
(preventing move), and as_str()
then unambiguously references it as a &str
.
Use match guard: match Some(a) { Some(ref s) if s == "hello" => … }
. Some(ref s)
matches any String
, and captures it as s: &String
, which you can then compare in the if
guard which does the usual flexible coercions to make it work.
See also: