Array::contains not respecting PartialEq<T>?


#1

Ok, steady the pitchforks for a minute. I’m not suggesting that I’m right, but my interpretation of the docs seems to indicate that I should be able to do something like this:

let list = [Cow::from("abc")];
list.contains(&"abc");

But if I run it (https://is.gd/ikzhYj) then apparently I can’t!

According to the docs, contains() takes a PartialEq<T>, and Cow has this implementation PartialEq<&'b str>. I’m confused as to how my code doesn’t satisfy those requirements.

Wisdom appreciated! :slight_smile:


#2

You have an array of T.
The type signature of contains is

fn contains(&self, x: &T) -> bool

So you must give it an &T. You can’t search for a string slice in an array of Cows.

The following where clause just states, that this function can only be used if the array type T implements PartialEq:

where T: PartialEq<T>

#3

Maybe the standard library is too restrictive here. Why is the signature of contains not like this?

fn contains<U>(&self, x: &U) -> bool
where U: PartialEq<T>

Then your example should work. I think.


#4

Ah! Yes, your suggestion was how I was reading the docs. I missed that T was already a Cow, rather than being a generic over whatever type I passed to contains().

Thanks mate!


#5

This is what we want to do, but didn’t (https://github.com/rust-lang/rust/pull/37761, and comment) because changing contains breaks type inference of many existing programs.