7

I'm attempting to write a data store in Rust that receives objects from JavaScript across the wasm-bindgen boundary and stores them for later retrieval. This is a simplified version of what I was hoping would work:

static mut MAP: HashMap<i32, String> = HashMap::new();

#[wasm_bindgen]
pub fn add_value(index: i32, value: String) {
    unsafe {
        MAP.insert(index, value);
    }
}

#[wasm_bindgen]
pub fn get_value(index: i32) -> String {
    unsafe {
        (*MAP.get(&index).unwrap()).clone()
    }
}

However I get this error from the Rust compiler:

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants

How can I store state so that subsequent calls across the wasm-bindgen boundary can retrieve previously stored values?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Adam R
  • 565
  • 4
  • 11
  • 1
    I believe your question is answered by the answers of [How do I create a global, mutable singleton?](https://stackoverflow.com/q/27791532/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 06 '18 at 19:02
  • 1
    Thank you - using lazy-static with a Mutex seems to be working. I'm good with marking this already answered. – Adam R Jul 06 '18 at 20:46

0 Answers0