Adr*_*let 1 string struct rust lazy-static
在 Rust 中,我试图声明一个自定义结构的静态实例。
因为默认情况下我不能分配 const 以外的其他值,所以我尝试使用lazy_static。
这是我的自定义结构:
pub struct MyStruct {
field1: String,
field2: String,
field3: u32
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试实例化它的方式:
lazy_static! {
static ref LATEST_STATE: MyStruct = {
field1: "".to_string(),
field2: "".to_string(),
field3: 0
};
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译并出现以下错误:
error: expected type, found `""``
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
尝试这个:
lazy_static! {
static ref LATEST_STATE: MyStruct = MyStruct {
// ^^^^^^^^
field1: "".to_string(),
field2: "".to_string(),
field3: 0
};
}
Run Code Online (Sandbox Code Playgroud)
Lazy_static 初始化与普通 Rust 相同。let mystruct: MyStruct = { field: "", ... };不会编译。您需要在 typename 之前,{}否则将其解释为代码块。
| 归档时间: |
|
| 查看次数: |
288 次 |
| 最近记录: |