对于`&str`,未实现`Borrow<String>`特性。

25

我正在尝试The Rust Programming Language一书中的一些示例,并有以下代码片段:

fn main() {
    let mut map: HashMap<&str, i32, RandomState> = HashMap::new();
    let hello: String = String::from("hello");
    map.insert(&hello, 100);
    println!("{:?}", map); //{"hello": 100}
    let first_hello_score: Option<&i32> = map.get("hello"); // This compiles
    let hello_score: Option<&i32> = map.get(&hello); // This does not compile
}

运行 cargo check 命令后,我看到:

error[E0277]: the trait bound `&str: Borrow<String>` is not satisfied
  --> src/main.rs:26:27
   |
26 |     let hello_score = map.get(&hello);
   |                           ^^^ the trait `Borrow<String>` is not implemented for `&str`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

有人能解释一下为什么会发生这种情况吗?

1个回答

36
.get查找参数&Q,其中键类型KBorrow<Q>。由于有一个将&T借用到&T的通用实现,因此可以将&str(键类型)借入&str(参数类型)中,并使内容更加通俗易懂。
然而,当使用&hello时,实际上是一个&String,这意味着Rust推断StringQ,因此它试图将&str借入&String中,这显然是不可能的。所以,请明确指出解引用强制转换,使Rust知道它应该将&String解引用为&str
let hello_score: Option<&i32> = map.get(&hello as &str);

或者,

let hello_score: Option<&i32> = map.get(&*hello);

4
应该使用解引用强制转换来处理 &String -> &str 的问题吗? - Anatoly Bugakov
get() 是一个通用方法。如果没有类型参数,键的类型将被确定为传递给该方法的值的类型。为了激活解引用强制转换,应该调用方法 HashMap::<&str, i32>::get::<str>(&map, &hello) - JUSEOK KO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接