A friend asked me to explain the following quirk in Rust. I could not, therefore this question:
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" }
Rust Playground Example
The compiler will complain as follows:
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`
In other words, &str does not force using &String .
At first I thought it was due to
'static , however it is a red herring.
The commented line captures the example due to the additional distribution.
My questions:
- Why does
&str not work with &String ? - Is there a way to make a call to
contains without extra allocation?
source share