Best way to call `vec.contains` in this case

I have: data: Vec<String> (unsorted) and some s: &str. I want to know if data contains s. To my surprise, data.contains(s) does not work because s is not &String. Note that BTreeMap::contains_key allows this.

Is data.iter().any(...) really my best option?

I believe it is.

Sort of surprising, but rational in essence:

// impl<T> [T]
pub fn contains(&self, x: &T) -> bool
where
    T: PartialEq<T>,

// impl<K, V, A> BTreeMap<K, V, A> where A: Allocator + Clone
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
    K: Borrow<Q> + Ord,
    Q: Ord + ?Sized, 

For Vec<String>, (&[String]).contains(&String) is the only form allowed by definition.
For BTreeMap<String, V, A>, btreemap.contains_key(&str) is acceptable because of String: Borrow<str> + Ord and str: Ord + ?Sized.

Sure, I understand the signatures. But it is surprising to me that they are the way they are. Probably for historic reasons? maybe because (earlier) type inference handles the non-Borrow one better?

1 Like

It was attempted but broke inference too much. See #42671 and the links within.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.