Rust lazy static custom struct instance

1.5k views Asked by At

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?

2

There are 2 answers

0
kmdreko On BEST ANSWER

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.

1
erick_ghz On

Instead of "".to_string() try to instantiate with String::from("").