创建静态变量时出错:'期望的标识符,找到`(`''

时间:2017-05-14 22:14:41

标签: rust

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

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的新手,所以我不知道这是不是真的。

1 个答案:

答案 0 :(得分:2)

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

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

根据Rust引用,静态绑定的语法定义如下:

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

可变静力学虽然不包括在内,但很可能被定义为包含 mut后的static

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

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

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

为此,您别无选择,只能使用模式来声明static或const变量。

在您之前的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模块上的文档提供了一些示例。