首页 > 解决方案 > 为什么 Rust HashMap 不允许使用“没有为结构 `HashMap` 找到名为 `insert` 的方法”插入值

问题描述

我有一个用空HashMapnode_type_odds)创建的结构。此哈希图将具有用户添加的值。

当我尝试在创建后使用fn set_node_odds它向哈希映射添加键和值时,并不建议使用insert关键字(据我了解)是键插入哈希映射的主要方式。

为什么我不能向结构中包含的哈希映射添加值?

use std::collections::HashMap;

//The possible node types
pub(crate) enum node_type {
    Kernel,
    LSTM,
    Perceptron,
}

//The possible activation types
pub(crate) enum activation_type {
    Binary,
    Linear,
    Sigmoid,
    Tan,
}

//The constructor that holds the seed values for the Mesh Networks.
pub(crate) struct constructor {
    node_type_default: node_type,
    node_type_odds: HashMap<node_type, f32>,
    activation_type: activation_type,
}

impl constructor {
    //Set the default node and initialize default values
    pub(crate) fn new() -> constructor {
        constructor {
            node_type_default: node_type::Perceptron,
            node_type_odds: HashMap::new(),
            activation_type: activation_type::Sigmoid,
        }
    }

    //Set the default node to a custom value
    pub(crate) fn set_default_node(&mut self, default_node: node_type) {
        self.node_type_default = default_node;
    }

    //Set the odds of each type of node to appear
    pub(crate) fn set_node_odds(&mut self, Type: node_type, Value: f32) {
        **//Here I attempt to insert a value with the key of type and a value of X.
  //Insert is not suggested however.**

        //THIS CODE SNIPPET DOES NOT WORK AS INSERT IS NOT SUGGESTED, IT IS HOWEVER THE INTENDED RESULT
        self.node_type_odds.insert(Type, Value);
    }
}
error[E0599]: no method named `insert` found for struct `std::collections::HashMap<constructor::node_type, f32>` in the current scope
  --> src/constructor.rs:45:29
   |
4  | pub(crate) enum node_type {
   | -------------------------
   | |
   | doesn't satisfy `constructor::node_type: std::cmp::Eq`
   | doesn't satisfy `constructor::node_type: std::hash::Hash`
...
45 |         self.node_type_odds.insert(node_type::Perceptron, 3 as f32);
   |                             ^^^^^^ method not found in `std::collections::HashMap<constructor::node_type, f32>`
   |
   = note: the method `insert` exists but the following trait bounds were not satisfied:
           `constructor::node_type: std::cmp::Eq`
           `constructor::node_type: std::hash::Hash`

标签: rusthashmap

解决方案


推荐阅读