stringstructrustlazy-static

Rust lazy static custom struct instance


In Rust, I am trying to declare a static instance of a custom struct.

Because by default I am not able to assign other values than const ones, I am trying to use lazy_static.

Here is my custom struct:

pub struct MyStruct { 
    field1: String,
    field2: String,
    field3: u32
}

Here is how I am trying to instantiate it:

lazy_static! {
    static ref LATEST_STATE: MyStruct = {
        field1: "".to_string(),
        field2: "".to_string(),
        field3: 0
    };
}

This code does not compile with the following error:

error: expected type, found `""``

What am I missing?


Solution

  • Try this:

    lazy_static! {
        static ref LATEST_STATE: MyStruct = MyStruct {
                                         // ^^^^^^^^
            field1: "".to_string(),
            field2: "".to_string(),
            field3: 0
        };
    }
    

    Lazy_static initialization is the same as normal Rust. let mystruct: MyStruct = { field: "", ... }; won't compile. You need the typename before the {} otherwise its interpreted as a code block.