【问题标题】:Can't use the insert() method不能使用 insert() 方法
【发布时间】:2021-09-27 18:22:15
【问题描述】:

我有一个很奇怪的问题:当我用 HashMap::new() 创建一个 HashMap 时,一切正常,但是当我用 HashMap::capacity_and_hasher 创建一个 hashmap 时,我不能使用插入方法

错误:

    |
 93 | map.insert(1,2);
    |     ^^^^^^ method cannot be called on `HashMap<_, _, &RandomState>` due to unsatisfied trait bounds
    |
   = note: the following trait bounds were not satisfied:
           `&RandomState: BuildHasher`

代码:

let s = RandomState::new();
let mut map = HashMap::with_hasher(&s);
map.insert(1,2);

【问题讨论】:

    标签: rust hashmap


    【解决方案1】:

    传递您的对象s RandomState 按值Playground

    通知HashMap::with_hasher(s);

    use std::collections::HashMap;
    use std::collections::hash_map::RandomState;
    
    fn main() {
        let s = RandomState::new();
        let mut map = HashMap::with_hasher(s);
        map.insert(1,2);
    }
    

    documentation of with_hasher 也提出了同样的建议

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2018-12-31
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2011-01-12
      相关资源
      最近更新 更多