A friend asked me to explain the following quirk in Rust. I was unable to, hence 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"
}
Example on the Rust Playground
The compiler will complain like this:
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 coerce with &String
.
At first I thought it was to do with 'static
, however that is a red herring.
The commented line fixes the example at the cost of an extra allocation.
My questions:
&str
coerce with &String
?contains
work without the extra allocation?The stick looks like it bends! This is due to light refraction. Light refraction is caused when the ray of light travels through different mediums and slows down or speeds up. In the case of this stick in the pool, water and air are two different mediums.
Bending a Pencil Science Explained Basically, the light refraction gives the pencil a slight magnifying effect, which makes the angle appear bigger than it actually is, causing the pencil to look crooked.
The change in the direction of a light ray on passing from one medium to another is called refraction. The bending of light takes place due to the difference in the optical densities of the two media.
As you sight through the side of the glass at the portion of the pencil located above the water's surface, light travels directly from the pencil to your eye. Since this light does not change medium, it will not refract. (Actually, there is a change of medium from air to glass and back into air.
It seems that the Rust developers intend to adjust the signature of contains
to allow the example posted above to work.
In some sense, this is a known bug in contains
. It sounds like the fix won't allow those types to coerce, but will allow the above example to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With