我是一个Rust初学者,正在尝试将当前用于测试字符串相等性的条件扩展到另一个字符串字面值,以便测试现在是是否包含在字符串字面值数组中。
在Python中,我只需要写string_to_test in ['foo','bar']
。 我如何将其移植到Rust?
这是我的尝试,但无法编译:
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或论坛上找到类似的问题。
["foo", "bar"].contains(&test_string)
这样写也完全没问题。 - Herohtarends_with(s)
等等。 - bmacnaughton