1

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?

Adrien Chapelet
  • 386
  • 4
  • 24

2 Answers2

8

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.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
1

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

erick_ghz
  • 19
  • 1