let mystring = format!("the quick brown {}", "fox...");
assert!(mystring.ends_with(mystring));
错误:
the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
将mystring.ends_with(mystring)
更改为mystring.ends_with(mystring.as_str())
可以修复它。
为什么这个错误如此神秘?
如果我在不使用格式的情况下创建字符串,请说:
let mystring = String::from_str("The quick brown fox...");
assert!(mystring.ends_with(mystring));
错误更容易理解:
error[E0599]: no method named `ends_with` found for type
`std::result::Result<std::string::String, std::string::ParseError>`
in the current scope
这个错误还有更多:
| assert!(mystring.ends_with(mystring));
| ^^^^^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
|
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
批判
注意:由于对
std::string::String
的std::str::pattern::Pattern<'_>
IMPL 的要求,因此需要
String
的.ends_with
接受任何实现Pattern
特征的值作为其搜索模式,而String
不实现该特征。
如果您查看Pattern
的文档,它包括
impl<'a, 'b> Pattern<'a> for &'b String
所以如果你改变,你的代码段工作正常
assert!(mystring.ends_with(mystring));
自
assert!(mystring.ends_with(&mystring));
这也是有道理的,因为否则你会试图将mystring
的所有权传递给ends_with
函数,这似乎不对。
至于你看到的具体错误,Pattern
的特质定义还包括
impl<'a, F> Pattern<'a> for F
where
F: FnMut(char) -> bool,
它通常表示函数接受 char 并将布尔计数作为模式返回,导致消息说String
与该特征实现不匹配。