测试Rust字符串是否包含在字符串数组中



我是一个Rust初学者,我正在尝试将当前测试字符串是否相等的条件扩展到另一个字符串字面量,以便现在测试字符串是否包含在字符串字面量数组中。

在Python中,我只写string_to_test in ['foo','bar']。我怎样才能把这个移植到铁锈上?

这是我的尝试,但这不能编译:

fn main() {
let test_string = "foo";
["foo", "bar"].iter().any(|s| s == test_string);
}

与错误:

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

不幸的是,我不能弄清楚这个问题,在StackOverflow或论坛上找不到类似的问题。

Herohtar建议一般解决方案:

["foo", "bar"].contains(&test_string) 

PitaJ在注释中建议使用这个简洁的宏,这只适用于编译时已知的标记,如注释中指出的Finomnis:

matches!(test_string, "foo" | "bar")

这就是我如何让我的代码工作:

["foo", "bar"].iter().any(|&s| s == test_string);

最新更新