代码之家  ›  专栏  ›  技术社区  ›  Paul C

对于简单类型不匹配[duplicate],获取错误“未为'std::string::string'实现特征'std::ops::FnMut<(char,)>”

  •  2
  • Paul C  · 技术社区  · 9 年前
        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
    
    1 回复  |  直到 9 年前
        1
  •  9
  •   loganfsmyth    9 年前

    还有更多错误:

    | 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::str::pattern::Pattern<'_> 对于 std::string::String

    String 's .ends_with Pattern 特征作为其搜索模式,以及 一串

    如果你看 the documentation for Pattern

    impl<'a, 'b> Pattern<'a> for &'b String
    

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

    assert!(mystring.ends_with(mystring));
    

    assert!(mystring.ends_with(&mystring));
    

    这也有道理,否则你会试图通过考试 属于 mystring ends_with 功能,这似乎不正确。

    图案 的特征定义还包括

    impl<'a, F> Pattern<'a> for F 
    where
        F: FnMut(char) -> bool, 
    

    这通常表示函数接受字符并返回布尔计数作为模式,导致消息说

    推荐文章