我正在尝试创建全局变量,但在此过程中遇到了多个编译错误。 首先我尝试了这个:
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 引用,静态绑定(bind)的语法定义如下:
static_item : "static" ident ':' type '=' expr ';' ;
可变静态,虽然没有包括在内,但很可能被定义为包括
静态
之后的mut
:
mut_static_item : "static" "mut" ident ':' type '=' expr ';' ;
编译器无法解析您的语句,因为它需要一个标识符,而不是一个模式。这与 let
绑定(bind)声明形成对比,后者接受关键字 let
之后的模式:
let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;
为此,您别无选择,只能不使用模式来声明 static 或 const 变量。
在您以前的 mpsc
channel 的情况下,即使这个限制也不能解决您的问题,因为静态绑定(bind)包含许多其他限制:例如考虑静态 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);
| ^^^^^^^^^^^^^^^^^^^^^^
channel 应该在本地创建,它们的端点从那里发送到其他线程。 mpsc
上的文档模块提供了一些示例。
关于rust - 创建静态变量时出错 : 'expected identifier, found ` (` ' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969314/