I'm relatively new to Rust and am trying to do the following:
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
}
}
}
When I try to build this, I get a compiler 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`
You should go back and re-read The Rust Programming Language, specifically the chapter on strings. String and &str are two different types.
You can create Strings in a number of ways, but I commonly use String::from:
let commands = [
String::from("one thing"),
String::from("another thing"),
String::from("something else"),
];
However, this is inefficient as you are allocating memory each time. It's better to instead go the other way, from &String to &str. Additionally, this doesn't solve your problem because you are attempting to compare a single value to a collection. We can solve both at once:
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
}
}
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With