为什么 BTreeMap<K, V> 的元素可以通过与 K 不同类型的 smth 得到,而 Vec 和 binary_search 却不是这样?
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?
我有个问题要问。我们来看看下面的代码:
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"));
}
因此,尽管 BTreeMap
保留 String
s,但它接受可以与密钥类型进行比较的其他类型。
但不只是 Vec<T>
的情况。因此,以下代码将是一个错误:
fn main() {
let v: Vec<String> = vec!["hello".to_owned()];
println!("{:?}", v.binary_search("hello"));
}
此代码段将无法编译,因为 binary_search
要求引用与所提供值完全相同的类型。我有点困惑为什么。
有 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.
实际上有点惊讶这没有被考虑用于新版本。我想 binary_search_by
提供了一个解决方法(正如上面@Dogbert 所评论的)这一事实已经让补救这个问题的优先级降低了。
我有个问题要问。我们来看看下面的代码:
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"));
}
因此,尽管 BTreeMap
保留 String
s,但它接受可以与密钥类型进行比较的其他类型。
但不只是 Vec<T>
的情况。因此,以下代码将是一个错误:
fn main() {
let v: Vec<String> = vec!["hello".to_owned()];
println!("{:?}", v.binary_search("hello"));
}
此代码段将无法编译,因为 binary_search
要求引用与所提供值完全相同的类型。我有点困惑为什么。
有 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.
实际上有点惊讶这没有被考虑用于新版本。我想 binary_search_by
提供了一个解决方法(正如上面@Dogbert 所评论的)这一事实已经让补救这个问题的优先级降低了。