我对Rust相对较新,我正在尝试执行以下操作:
pub fn route(request: &[String]) {
let commands = ["one thing", "another thing", "something else"];
for command in commands.iter() {
if command == request {
// do something
} else {
// throw error
}
}
}
当我尝试构建它时,我收到编译器错误:
error[E0277]: the trait bound `&str: std::cmp::PartialEq<[std::string::String]>` is not satisfied
--> src/main.rs:5:20
|
5 | if command == request {
| ^^ can't compare `&str` with `[std::string::String]`
|
= help: the trait `std::cmp::PartialEq<[std::string::String]>` is not implemented for `&str`
= note: required because of the requirements on the impl of `std::cmp::PartialEq<&[std::string::String]>` for `&&str`
答案 0 :(得分:3)
您应该返回并重新阅读The Rust Programming Language,特别是chapter on strings。 String
和&str
两种不同类型。
您可以在number of ways中创建String
,但我通常使用String::from
:
let commands = [
String::from("one thing"),
String::from("another thing"),
String::from("something else"),
];
但是,由于每次都在分配内存,因此效率很低。从&String
到&str
,反而采取相反的方式会更好。此外,这并不能解决您的问题,因为您试图将单个值与集合进行比较。我们可以同时解决这两个问题:
let commands = ["one thing", "another thing", "something else"];
for command in commands.iter() {
if request.iter().any(|r| r == command) {
// do something
} else {
// throw error
}
}
另见: