从技术上讲,您没有String
s ( &[String]
)的切片,而是有s ( ) 的数组。String
[String; 2]
让我们看一个较小的案例:
fn main() {
match "foo".to_owned() {
"foo" => println!("matched"),
_ => unreachable!(),
}
}
在这里,我们得到相同的错误消息:
error[E0308]: mismatched types
--> src/main.rs:3:9
|
3 | "foo" => println!("matched"),
| ^^^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
在这种情况下,解决方法是将 更改String
为 a &str
,这是切片模式所理解的:
let s = "foo".to_owned();
match s.as_str() {
"foo" => println!("matched"),
_ => unreachable!(),
}
也可以看看:
那么,我们如何将其扩展到您的示例?直截了当的事情是两次做同样的事情:
fn main() {
let x = ["foo".to_owned(), "bar".to_owned()];
match [x[0].as_str(), x[1].as_str()] {
["foo", y] => println!("y is {}.", y),
_ => unreachable!(),
}
}
但是,这不适用于切片 ( &[T]
) 的情况,因为我们只处理两个值,而不是任意数量。在这种情况下,我们需要做一个临时的Vec
:
fn main() {
let x = ["foo".to_owned(), "bar".to_owned()];
let x2: Vec<_> = x.iter().map(|x| x.as_str()).collect();
match x2.as_slice() {
["foo", y] => println!("y is {}.", y),
_ => unreachable!(),
}
}
请注意,您必须将 转换Vec
为切片本身 ( x2.as_slice()
),因为切片模式只能理解切片。