gpt4 book ai didi

rust - 如何使用 lazy_static!在结构实现中?

转载 作者:行者123 更新时间:2023-11-29 08:31:46 30 4
gpt4 key购买 nike

#[derive(Serialize)]
pub struct SLPInfoVersion {
name: String,
protocol: i32
}

impl SLPInfoVersion {
lazy_static! {
pub static ref V1_13: MyStruct = (SLPInfoVersion {
name: "1.13".to_string(),
protocol: 404
});
}
}

lazy_static! 调用给我这个错误:

error: expected one of `(`, `async`, `const`, `default`, `existential`, `extern`, `fn`, `type`, or `unsafe`, found `struct`                      
--> src\protocol\packet\mod.rs:244:2
|
244 | lazy_static! {
| _____^
| |_____|
| ||_____|
| |||
245 | ||| pub static ref V1_13: SLPInfoVersion = (SLPInfoVersion {
246 | ||| name: "1.13".to_string(),
247 | ||| protocol: 404
248 | ||| });
249 | ||| }
| ||| ^
| |||_____|
| ||______expected one of 9 possible tokens here
| |_______unexpected token
| in this macro invocation
|
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

我正在使用 Rust 1.32.0。

最佳答案

你不能。 lazy-static 通过创建一个新的隐藏类型以及该类型的 static 变量来工作。这些都不允许在 impl block 中创建:

struct Foo;

impl Foo {
static BAR: u8;

struct Bar;
}
error: expected one of `async`, `const`, `crate`, `default`, `existential`, `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `static`
--> src/lib.rs:4:5
|
3 | impl Foo {
| - expected one of 11 possible tokens here
4 | static BAR: u8;
| ^^^^^^ unexpected token

error: expected one of `async`, `const`, `crate`, `default`, `existential`, `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `struct`
--> src/lib.rs:6:5
|
4 | static BAR: u8;
| - expected one of 11 possible tokens here
5 |
6 | struct Bar;
| ^^^^^^ unexpected token

相反,在 impl block 外部或函数内部使用它。

另见:

关于rust - 如何使用 lazy_static!在结构实现中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984384/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com