【问题标题】:A Hashmap supporting String and &str支持 String 和 &str 的 Hashmap
【发布时间】:2019-06-20 03:23:59
【问题描述】:

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

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

【问题讨论】:

    标签: rust borrowing copy-on-write run-time-polymorphism


    【解决方案1】:

    抽象数据是借用还是拥有的内置方法是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
    }
    

    &amp;strString 都可以使用 .into() 转换为 Cow&lt;str&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2013-02-20
      • 2018-12-06
      • 1970-01-01
      相关资源
      最近更新 更多