代码之家  ›  专栏  ›  技术社区  ›  Grandma Kisses

如何在rust中使用struct制作一种哈希映射

  •  1
  • Grandma Kisses  · 技术社区  · 4 年前

    我是个新手,希望能像这样在我的结构中实现我的hashmap

    #[derive(Clone, Data)]
    struct CheckState { 
        cool: String,
        int_cool: i32,
        hashmap_cool: HashMap<i32, String>
    }
    
    

    但我一直收到错误代码 error[E0277]: the trait bound `HashMap<i32, std::string::String>: Data` is not satisfied 我不明白为什么,而且帮助也不多

    铁锈有助于

     help: the following other types implement trait `Data`:
                &'static str
                ()
                (T0, T1)
                (T0, T1, T2)
                (T0, T1, T2, T3)
                (T0, T1, T2, T3, T4)
                (T0, T1, T2, T3, T4, T5)
                (T0,)
              and 87 others
      = note: this error originates in the derive macro `Data` (in Nightly builds, run with -Z macro-backtrace for more info)
    

    请忽略变量名,它们在我的代码中不一样

    1 回复  |  直到 4 年前
        1
  •  2
  •   Jonathan Coletti    4 年前

    你好,请添加一个简单的补丁

    struct CheckState { 
        cool: String,
        int_cool: i32,
        #[data(ignore)]
        hashmap_cool: HashMap<i32, String>
    }
    

    请参阅下面的德鲁伊文档,以便更好地理解

    druid_derive
    proc_macro Data
    Generates implementations of the Data trait.
    
    This macro supports a data field attribute with the following arguments:
    
    #[data(ignore)] makes the generated Data::same function skip comparing this field.
    #[data(same_fn="foo")] uses the function foo for comparing this field. foo should be the name of a function with signature fn(&T, &T) -> bool, where T is the type of the field.
    
    推荐文章