1

在 Rust 中,我试图声明一个自定义结构的静态实例。

因为默认情况下我无法分配 const 以外的其他值,所以我尝试使用lazy_static。

这是我的自定义结构:

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

这是我尝试实例化它的方式:

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

此代码无法编译并出现以下错误:

error: expected type, found `""``

我错过了什么?

4

2 回答 2

8

试试这个:

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

Lazy_static 初始化与普通的 Rust 相同。let mystruct: MyStruct = { field: "", ... };不会编译。{}在将其解释为代码块之前,您需要类型名。

于 2020-10-18T17:02:25.770 回答
1

而不是"".to_string()尝试用String::from("").

于 2020-11-06T05:07:02.010 回答