一个朋友问我解释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"
}
编译器会报出以下错误信息:
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`
换句话说,&str
不能与&String
强制转换。
起初我认为这与'static
有关,但那是一个误导。
注释掉的行会以额外的分配成本修复示例。
我的问题:
- 为什么
&str
不能与&String
强制转换? - 有没有办法使调用
contains
不需要额外的分配?
String
和str
之间的区别?的重复问题。 - Nikolay LebedevString
和str
之间的区别。这是一个强制转换的问题。 - Edd Barrettstr
强制转换为String
没有意义,以及您如何更改代码以避免分配。 - Marko Popovic