创建静态变量时出错:'expected identifier, found `(` '



我正在尝试创建全局变量,但在此过程中遇到了多个编译错误。 首先我尝试了这个:

static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel();
error: expected identifier, found `(`
|
109 | static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel();
^
|

然后我尝试了一些其他形式,但似乎它们总是给我一个类似的错误:

thread_local!(static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel());
error: no rules expected the token `(`
|
109 | thread_local!(static mut (tx, rx): (mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel());
^
|

最后,如果这有助于其他人做出回应,它也会发生:

static (x, y, z) = (1, 2, 3);
error: expected identifier, found `(`
|
109 | static (x, y, z) = (1, 2, 3);
|        ^

也许从静态声明创建元组时有些错误,但我是 Rust 的新手,所以我不知道这是否属实。

正如您在上次尝试中发现的那样,可以更轻松地重现相同的问题:

static (A, B): (i32, i32) = (1, 2);

根据 Rust 参考,静态绑定的语法定义如下:

static_item : "static" ident ':' type '=' expr ';' ;

可变静态,虽然不包括在内,但最有可能定义为包括staticmut

mut_static_item : "static" "mut" ident ':' type '=' expr ';' ;

编译器无法分析语句,因为它需要标识符,而不是模式。这与let绑定声明形成对比,后者接受关键字let之后的模式:

let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;

为此,您别无选择,只能不使用模式来声明静态或常量变量。

在以前mpsc通道的情况下,即使这个限制也不能解决你的问题,因为静态绑定包含许多其他限制:例如考虑静态Vec的声明:

static moo: Vec<i32> = Vec::with_capacity(10);

这将产生以下错误:

error[E0015]: calls in statics are limited to struct and enum constructors
--> src/main.rs:1:24
|
1 | static moo: Vec<i32> = Vec::with_capacity(10);
|                        ^^^^^^^^^^^^^^^^^^^^^^

通道旨在在本地创建,其端点从那里发送到其他线程。有关mpsc模块的文档提供了一些示例。

最新更新