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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Probably even better nowadays is String::default()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.