简体   繁体   中英

Associated type binding not allowed in lazy_static Rust

I'd like to create a HashMap with lazy_static , but can't seem to provide the right type arguments:

use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref DROPPABLES: Mutex<HashMap<String, D: DroppableExt>> = Mutex::new(HashMap::new());
}
pub trait DroppableExt: DynClone+Send{
    fn droppable_id(&self)->String; 
}

gives error:

error[E0229]: associated type bindings are not allowed here
  --> src\main.rs:56:54
   |
56 |     static ref NEW_DROPPABLES: Mutex<HashMap<String, D: DroppableExt>> = Mutex::new(HashMap::new()) ;
   |                                                      ^^^^^^^^^^^^^^^ associated type not allowed here

What am I doing wrong here? I just want require that all the HashMap values have a type with implements DroppableExt .

You'd get the same error if you tried to do this

fn main() {
    let DROPPABLES: Mutex<HashMap<String, D: DroppableExt>>;
}

so this has nothing to do with lazy_static . If you want DROPPABLES to handle values of different types as long as they implement DroppableExt , you can use trait objects :

use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref DROPPABLES: Mutex<HashMap<String, Box<dyn DroppableExt>>> = Mutex::new(HashMap::new());
    //                                           ^^^
    // note that you'll have to box anything you want to store in DROPPABLES now
}
pub trait DroppableExt: DynClone+Send{
    fn droppable_id(&self)->String; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM