为什么使用Vec :: contains时&str不会强制转换为&String?

Edd*_*ett 5 string rust

一位朋友让我解释Rust中的以下怪癖.我无法,因此这个问题:

fn main() {
    let l: Vec<String> = Vec::new();
    //let ret = l.contains(&String::from(func())); // works
    let ret = l.contains(func());  // does not work
    println!("ret: {}", ret);
}

fn func() -> & 'static str {
    "hello"
}
Run Code Online (Sandbox Code Playgroud)

Rust Playground上的示例

编译器会这样抱怨:

error[E0308]: mismatched types
 --> src/main.rs:4:26
  |
4 |     let ret = l.contains(func());  // does not work
  |                          ^^^^^^ expected struct `std::string::String`, found str
  |
  = note: expected type `&std::string::String`
             found type `&'static str`
Run Code Online (Sandbox Code Playgroud)

换句话说,&str不强迫&String.

起初我认为这是与之相关的'static,但这是一个红鲱鱼.

注释行以额外分配为代价修复了示例.

我的问题:

  • 为什么不&str强迫&String
  • 有没有办法让呼叫在contains没有额外分配的情况下工作?

Edd*_*ett 7

Rust 开发人员似乎打算调整 的签名,contains以允许上面发布的示例正常工作

从某种意义上说,这是contains. 听起来修复不会允许这些类型强制,但将允许上面的示例工作。


hel*_*low 6

你的第一个问题应该由@Marko回答.

你的第二个问题也应该很容易回答,只需使用一个闭包:

let ret = l.iter().any(|x| x == func());

编辑:

不再是"真正的"答案了,但我在这里为那些可能对此解决方案感兴趣的人提供了这个答案.