我是一个完整的Rust新手,所以请注意,可能会出现愚蠢的语法错误。 :)
我在Rust中编写教程,因为我自己学习,而我尝试做的是将元组分解为变量,然后通过错误地提到其中一种类型导致错误:
fn main() {
let tup = (500, 6.4, 1);
let (x: bool, y: f32, z: i16) = tup;
println!("{}, {}, {}", x, y, z);
}
我的想法是编译器会引发错误,因为x
被赋予bool
但与500
匹配。令人惊讶的是,它是编译器抱怨的最后一个语句,说在此范围内找不到x,y和z。
我尝试了另一种方式:
fn main() {
let tup = (500, 6.4, 1);
let mut x: bool = true;
let mut y: f32 = true;
let mut z: i16 = true;
(x, y, z) = tup;
println!("{}, {}, {}", x, y, z);
}
这一次,编译器确实引发了预期的错误,但它也说(x, y, z) = tup;
的左侧不是有效的。有人能解释一下发生了什么吗?
答案 0 :(得分:10)
答案 1 :(得分:3)
您需要更仔细地阅读错误;第一个案例的第一个案例是:
error: expected one of `)`, `,`, or `@`, found `:`
--> src/main.rs:3:11
|
3 | let (x: bool, y: f32, z: i16) = tup;
| ^ expected one of `)`, `,`, or `@` here
这表示当您对元组进行模式匹配时,无法在变量名称旁边提供类型。这是一个解析错误,导致整行无效并导致x
,y
和z
无法在println!()
中找到:
error[E0425]: cannot find value `x` in this scope
--> src/main.rs:4:28
|
4 | println!("{}, {}, {}", x, y, z);
| ^ not found in this scope
error[E0425]: cannot find value `y` in this scope
--> src/main.rs:4:31
|
4 | println!("{}, {}, {}", x, y, z);
| ^ not found in this scope
error[E0425]: cannot find value `z` in this scope
--> src/main.rs:4:34
|
4 | println!("{}, {}, {}", x, y, z);
| ^ not found in this scope
至于第二种情况,有一堆无效的任务; y
和z
是数字,但您尝试将bool
分配给它们; (x, y, z) = ...
也是一个无效的赋值 - 它不会模式匹配,除非它在let
绑定中。