Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a &str not coerce to a &String when using Vec::contains?

Tags:

string

rust

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:

  • Why doesn't &str coerce with &String?
  • Is there a way to make the call to contains work without the extra allocation?
like image 303
Edd Barrett Avatar asked Feb 26 '18 10:02

Edd Barrett


People also ask

Why does a stick look bent in water?

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.

Why does the pencil appear to be bent?

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.

Why does refraction occur?

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.

What happens when you look at the pencil through the side of the glass?

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.


1 Answers

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.

like image 51
Edd Barrett Avatar answered Nov 16 '22 02:11

Edd Barrett