如何将元组解构为类型化变量? [英] How can I destructure tuples into typed variables?

查看:56
本文介绍了如何将元组解构为类型化变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将元组分解为变量,然后通过错误提到的类型之一导致错误:

I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}

我的想法是编译器会引发错误,因为 xbool 形式给出,但与 500 匹配.令人惊讶的是,这是编译器抱怨的最后一条语句,说在此范围内找不到 x、y 和 z:

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

我尝试了另一种方式:

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; 的左侧无效.有人能解释一下发生了什么吗?

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?

推荐答案

你需要更仔细地阅读错误;第一个案例的第一个是:

You need to read the errors more carefully; the first case's very first one was:

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

这表明当您对元组进行模式匹配时,您不能在变量名称旁边提供类型.这是一个解析错误,导致整行无效,并导致 xyz 无法用于 println!():

Which indicates that you can't provide types next to the variable names when you pattern match against a tuple. This is a parsing error which rendered that whole line invalid and caused x, y and z not to be found for the purposes of 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

对于第二种情况,有一堆无效的赋值;yz 是数字,但是您尝试将 bool 分配给它们;(x, y, z) = ... 也是一个无效的赋值——除非它在一个 let 绑定中,否则它不会模式匹配.

As for the second case, there's a bunch of invalid assignments; y and z are numbers, but you try to assign bools to them; (x, y, z) = ... is also an invalid assignment - it doesn't pattern match unless it's within a let binding.

这篇关于如何将元组解构为类型化变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆