获取错误"特征`std :: ops :: FnMut <(char,)>`没有为`std :: string :: String`"实现简单类型不匹配

mar*_*hon 2 rust

    let mystring = format!("the quick brown {}", "fox...");
    assert!(mystring.ends_with(mystring));
Run Code Online (Sandbox Code Playgroud)

错误:

the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
Run Code Online (Sandbox Code Playgroud)

改变mystring.ends_with(mystring)mystring.ends_with(mystring.as_str())修复它.

为什么这个错误如此神秘?

如果我在不使用格式的情况下创建字符串,请说:

let mystring = String::from_str("The quick brown fox...");
assert!(mystring.ends_with(mystring));
Run Code Online (Sandbox Code Playgroud)

错误更容易理解:

error[E0599]: no method named `ends_with` found for type
`std::result::Result<std::string::String, std::string::ParseError>`
in the current scope
Run Code Online (Sandbox Code Playgroud)

log*_*yth 8

这个错误还有更多:

| 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`
Run Code Online (Sandbox Code Playgroud)

危重

注意:需要的,因为上的IMPL要求std::str::pattern::Pattern<'_>std::string::String

String.ends_with接受任何实现Pattern特征作为其搜索模式的值,并且String不实现该特征.

如果你查看文档Pattern,它包括

impl<'a, 'b> Pattern<'a> for &'b String
Run Code Online (Sandbox Code Playgroud)

因此,如果您更改,您的代码段工作正常

assert!(mystring.ends_with(mystring));
Run Code Online (Sandbox Code Playgroud)

assert!(mystring.ends_with(&mystring));
Run Code Online (Sandbox Code Playgroud)

这也有道理,否则你会试图通过所有权mystringends_with功能,这看起来不正确.

至于你看到的具体错误,Pattern特征定义还包括

impl<'a, F> Pattern<'a> for F 
where
    F: FnMut(char) -> bool, 
Run Code Online (Sandbox Code Playgroud)

它通常表示函数接受一个char并返回一个布尔计数作为模式,导致消息说String与该特征实现不匹配.