一位朋友让我解释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)
编译器会这样抱怨:
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没有额外分配的情况下工作?你的第一个问题应该由@Marko回答.
你的第二个问题也应该很容易回答,只需使用一个闭包:
let ret = l.iter().any(|x| x == func());
不再是"真正的"答案了,但我在这里为那些可能对此解决方案感兴趣的人提供了这个答案.
| 归档时间: |
|
| 查看次数: |
280 次 |
| 最近记录: |