1

如何定义同时支持其键和内容String的HashMap?&str我尝试了以下方法:

fn mapping<T: Into<String>>() -> HashMap<T, T> {
  let mut map: HashMap<T, T> = HashMap::new();
  map.insert("first_name", "MyFirstName");
  map.insert("last_name".to_string(), "MyLastName".to_string());
  map
}

fn main() {
  let mut mapping = mapping();
}

但它没有编译,说:

error[E0599]: no method named `insert` found for type `std::collections::HashMap<T, T>` in the current scope
error[E0277]: the trait bound `T: std::cmp::Eq` is not satisfied
error[E0277]: the trait bound `T: std::hash::Hash` is not satisfied
4

1 回答 1

3

抽象数据是借用还是拥有的内置方法是Cow.

use std::borrow::Cow;
use std::collections::HashMap;

fn mapping() -> HashMap<Cow<'static, str>, Cow<'static, str>> {
    let mut map = HashMap::new();
    map.insert("first_name".into(), "MyFirstName".into());
    map.insert("last_name".to_string().into(), "MyLastName".to_string().into());
    map
}

两者&strString都可以转换为Cow<str>using .into()

于 2019-06-20T11:31:47.263 回答