I'm a Rust beginner and I'm trying to extend a condition that currently tests a string for equality to another string literal, so that the test is now whether the string is contained in an array of string literals.
In Python, I would just write string_to_test in ['foo','bar']
. How can I port this to rust?
Here's my attempt, but this doesn't compile:
fn main() {
let test_string = "foo";
["foo", "bar"].iter().any(|s| s == test_string);
}
with errors:
Compiling playground v0.0.1 (/playground)
error[E0277]: can't compare `&str` with `str`
--> src/main.rs:3:35
|
3 | ["foo", "bar"].iter().any(|s| s == test_string);
| ^^ no implementation for `&str == str`
|
= help: the trait `PartialEq<str>` is not implemented for `&str`
= note: required because of the requirements on the impl of `PartialEq<&str>` for `&&str`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error
I can't figure this out unfortunately and couldn't find a similar question on StackOverflow or forums.
Herohtar suggested the general solution:
["foo", "bar"].contains(&test_string)
PitaJ suggested this terse macro in a comment, this works only with tokens known at compile time as Finomnis noted in a comment:
matches!(test_string, "foo" | "bar")
This is how I got my code to work:
["foo", "bar"].iter().any(|&s| s == test_string);