0

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.

2
  • 1
    A single HashMap can't store values of different types. You probably can use Box<dyn DroppableExt>, if the dynamic dispatch and the inability to do anything not described by the trait suits you. Commented Jul 5, 2021 at 4:49
  • Can you define such a hashmap without lazy_static? Commented Jul 5, 2021 at 6:00

1 Answer 1

2

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; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.