Match a slice of str or String

You can't match a String against a string slice directly, and you can't do it on the other side of a trait or generic either. Rust's pattern matching mechanism requires you to be able to write out the constructor for the type in the pattern, so you can't match a trait, a generic parameter, or the internal structure of a type with private internals, because the constructor is abstracted away.

Your .as_foo() idea is the best way to do this, because it allows you to convert the type into something you can construct.

Alternatively, you can do something like this, but it does an allocation:


pub fn info1<'a, S>(path: &[S]) -> Option<String>
where
  S: AsRef<str>,
{
  match &path.iter().map(|s| s.as_ref()).collect::<Vec<_>>()[..] {
    ["a", "b"] => Some("It's a b!".to_string()),
    _ => None,
  }
}