获取简单类型不匹配的错误"the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`


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::Stringstd::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与该特征实现不匹配。

相关内容

最新更新