我试图理解HashMaps在Rust中是如何工作的,我给出了这个例子.

use std::collections::HashMap;

fn main() {
    let mut roman2number: HashMap<&'static str, i32> = HashMap::new();
    roman2number.insert("X", 10);
    roman2number.insert("I", 1);

    let roman_num = "XXI".to_string();
    let r0 = roman_num.chars().take(1).collect::<String>();
    let r1: &str = &r0.to_string();
    println!("{:?}", roman2number.get(r1)); // This works

    // println!("{:?}", roman2number.get(&r0.to_string())); // This doesn't
}

当我试图在最后一行未注释的情况下编译代码时,我得到了以下错误

error: the trait bound `&str: std::borrow::Borrow<std::string::String>` is not satisfied [E0277]
println!("{:?}", roman2number.get(&r0.to_string()));
                                            ^~~
note: in this expansion of format_args!
note: in this expansion of print! (defined in <std macros>)
note: in this expansion of println! (defined in <std macros>)
help: run `rustc --explain E0277` to see a detailed explanation

docs的Trait实现部分给出了fn deref(&self) -> &str的解引用

那么这里发生了什么?

推荐答案

该错误是由编译器在类型推断期间 Select 泛型函数HashMap::get over String引起的.但你想要HashMap::getstr.

所以只要改变

println!("{:?}", roman2number.get(&r0.到_string()));

println!("{:?}", roman2number.get::<str>(&r0.到_string()));

到 make it explicit. This helps the compiler 到 select the right function.

看看Playground here.

It looks 到 me that coercion Deref<Target> can only happen when we know the target type, so when compiler is trying 到 infer which HashMap::get 到 use, it sees &r0.到_string() as type &String but never &str. And &'static str does not implement Borrow<String>. This results a type error. When we specify HashMap::get::<str>, this function expects &str, when coercion can be applied 到 &String 到 get a matching &str.

你可以查看Deref coercionString Deref了解更多细节.

Rust相关问答推荐

为什么幻影数据不能自动推断?

MacOS(AARCH64)上Ghidra中的二进制补丁导致进程终止

在UdpSocket上使用sendto时的隐式套接字绑定

当对VEC;U8>;使用serde_json时,Base64编码是保护空间的好方法吗?

为什么铁 rust S的默认排序功能比我对小数组的 Select 排序稍微慢一些?

循环访问枚举中的不同集合

为什么 vec![Vec::with_capacity(n)] 为子向量创建 0 容量?

为什么 js_sys Promise::new 需要 FnMut?

Rust Option 的空显式泛型参数

我可以用 Rust 编写一个不可变变量

中文优化标题:跳出特定循环并返回一个值

`tokio::pin` 如何改变变量的类型?

push 方法是否取得所有权?

如何在 Rust 中将枚举变体转换为 u8?

Rust:`sort_by` 多个条件,冗长的模式匹配

在 Rust 中,为什么整数溢出有时会导致编译错误或运行时错误?

如何使返回 XMLError 的方法与 anyhow::Error 兼容?

为什么可以从闭包中返回私有 struct

在 Rust 中组合特征的不同方法是否等效?

基于名称是否存在的条件编译