ANimator120
ANimator120

Reputation: 3441

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.

Upvotes: 0

Views: 339

Answers (1)

isaactfa
isaactfa

Reputation: 6657

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; 
}

Upvotes: 2

Related Questions