add zh/tuple.md

This commit is contained in:
sunface 2022-02-27 22:16:13 +08:00
parent 18ddf5cbe8
commit 10cf4d8bad
2 changed files with 80 additions and 3 deletions

View File

@ -31,7 +31,7 @@ fn main() {
}
```
🌟 Destructuring tuple with patter.
🌟 Destructuring tuple with pattern.
```rust,editable
fn main() {
@ -51,6 +51,7 @@ fn main() {
fn main() {
let (x, y, z);
// fill the blank
__ = (1, 2, 3);
assert_eq!(x, 3);
@ -63,7 +64,7 @@ fn main() {
```rust,editable
fn main() {
// fill the blank to make it work
// fill the blank, need a few computations here.
let (x, y) = sum_multiply(__);
assert_eq!(x, 5);

View File

@ -1 +1,77 @@
# tuple
# 元组( Tuple )
🌟 元组中的元素可以是不同的类型。元组的类型签名是 `(T1, T2, ...)`, 这里 `T1`, `T2` 是相对应的元组成员的类型.
```rust,editable
fn main() {
let _t0: (u8,i16) = (0, -1);
// 元组的成员还可以是一个元组
let _t1: (u8, (i16, u32)) = (0, (-1, 1));
// 填空让代码工作
let t: (u8, __, i64, __, __) = (1u8, 2u16, 3i64, "hello", String::from(", world"));
}
```
🌟 可以使用索引来获取元组的成员
```rust,editable
// 修改合适的地方,让代码工作
fn main() {
let t = ("i", "am", "sunface");
assert_eq!(t.1, "sunface");
}
```
🌟 过长的元组无法被打印输出
```rust,editable
// 修复代码错误
fn main() {
let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
println!("too long tuple: {:?}", too_long_tuple);
}
```
🌟 使用模式匹配来解构元组
```rust,editable
fn main() {
let tup = (1, 6.4, "hello");
// 填空
let __ = tup;
assert_eq!(x, 1);
assert_eq!(y, "hello");
assert_eq!(z, 6.4);
}
```
🌟🌟 解构式赋值
```rust,editable
fn main() {
let (x, y, z);
// 填空
__ = (1, 2, 3);
assert_eq!(x, 3);
assert_eq!(y, 1);
assert_eq!(z, 2);
}
```
🌟🌟 元组可以用于函数的参数和返回值
```rust,editable
fn main() {
// 填空,需要稍微计算下
let (x, y) = sum_multiply(__);
assert_eq!(x, 5);
assert_eq!(y, 6);
}
fn sum_multiply(nums: (i32, i32)) -> (i32, i32) {
(nums.0 + nums.1, nums.0 * nums.1)
}
```