unegare
unegare

Reputation: 2579

Why elements of BTreeMap<K, V> can be got by smth of different type than K, but it's not the case with Vec and binary_search?

I have a question to ask. Let's take a look at the following code:

use std::collection::BTreeMap;

fn main() {
  let mut hm: BTreeMap<String, String> = BTreeMap::new();
  hm.insert("asdf".to_owned(), "zxcv".to_owned());
  println!("{:?}", hm.get("asdf"));
}

So, despite the fact that BTreeMap keeps Strings it accepts other types which can be compared to the key type.

But it's not just the case with Vec<T>. Hence the following code would be a blunder:

fn main() {
  let v: Vec<String> = vec!["hello".to_owned()];
  println!("{:?}", v.binary_search("hello"));
}

This snippet would just fail to be compiled, since binary_search calls for a reference to the exactly same type of the provided value. I'm somewhat bewildered why.

Upvotes: 2

Views: 87

Answers (1)

eggyal
eggyal

Reputation: 125865

There was an attempt to change the signature of binary_search to support accepting a borrowed version of the value but it broke stuff and was declined.

Actually a little surprised this wasn't considered for a new edition. I guess the fact that binary_search_by provides a workaround (as commented by @Dogbert above) has left remedying this a low priority.

Upvotes: 5

Related Questions