These are chat archives for rust-lang/rust

16th
Jan 2019
wegry
@wegry
Jan 16 11:02
Hey, I'm trying to pass in json to a static global and then trying to reference that.
use wasm_bindgen::prelude::*;

static mut METADATA: Option<&[BundledNode]> = None;

#[wasm_bindgen]
pub fn init(meta_json: &str) {
    let meta: Vec<BundledNode> =
        serde_json::from_str(meta_json).expect("Unable to deserialize data provided on init(...)");

    // This is pretty sketchy, a mutex would be good here instead
    unsafe {
        METADATA = Some(meta);
    }
}

#[wasm_bindgen]
pub fn render() -> String {
    let source = unsafe { METADATA.unwrap().clone() };

    graph::html_render(&source, false)
}
If I make the type of METADATA Option<Vec<BundledNode>> then when I go to read the blob, the compiler throws out
[rustc]
cannot move out of static item

cannot move out of static item [E0507]
lib.rs(25, 27): cannot move out of static item
wegry
@wegry
Jan 16 11:24
https://stackoverflow.com/a/27826181/1924257 looks like it might solve my problem?
Denis Lisov
@tanriol
Jan 16 11:26
Are you sure you want to keep that information in a static (of some kind)? Is it possible that your user wants to use multiple different metadata objects?
wegry
@wegry
Jan 16 11:37
@tanriol I'm pretty sure, because the use case of the this is embedded in a page hosted on a local file system.
I have an initial HTML page (and accompanying JS) generated by a cli tool.
the JS data has to be passed back to the WASM lib to rerender a changed modified version of the HTML graph
Denis Lisov
@tanriol
Jan 16 11:40
You can try METADATA.as_ref().unwrap()
wegry
@wegry
Jan 16 11:43
I appreciate it.
Denis Lisov
@tanriol
Jan 16 12:21
Should work. Have you written Ok(...); by mistake?
Ingvar Stepanyan
@RReverser
Jan 16 12:22

&text.to_string()

Offtop, but this looks odd - you're essentially taking a String, then a reference to it, then convert (clone) into another String, and then take a reference of that

You should just use &text
Denis Lisov
@tanriol
Jan 16 12:36
pub fn deserialized(text:String) -> Result<models::ServerModel,Error> {
        let model: models::ServerModel = serde_json::from_str(&text)?;
        Ok(model)
}
Note there's no unwrap in my snippet :-)
The question mark replaces it by either leaving the Ok value for you to work with or directly returning the Err error (possibly converting it with From to make error types match)
laurent bernabé
@loloof64
Jan 16 20:30
Thanks @tanriol and @omni-viral for your suggestions (sorry for this late answer).
I can try to adapt it so that it does not panic and make a PR indeed :smile: But I'm not yet really used to the rust language (particularly closures are the trickiest feature I am facing, if I remove all other advance features like traits and macros)
laurent bernabé
@loloof64
Jan 16 20:44
@omni-viral Thanks again :smile: I forgot that semi-column ...
Zakarum
@omni-viral
Jan 16 20:48
@loloof64 you're welcome