- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 149字
- 2021-07-02 13:35:17
Tuples
Tuples differ from arrays in the way that elements of an array have to be of the same type, while items in a tuple can be a mix of types. They are heterogeneous collections and are useful for storing distinct types together. They can also be used when returning multiple values from a function. Consider the following code that uses tuples:
// tuples.rs
fn main() {
let num_and_str: (u8, &str) = (40, "Have a good day!");
println!("{:?}", num_and_str);
let (num, string) = num_and_str;
println!("From tuple: Number: {}, String: {}", num, string);
}
In the preceding code, num_and_str is a tuple of two items, (u8, &str). We can also extract values from an already declared tuple into individual variables. After printing the tuple, we destructure it on the next line into the num and string variables, and their types are inferred automatically. That's pretty neat.
推薦閱讀
- Apache ZooKeeper Essentials
- PWA入門與實(shí)踐
- Building a Game with Unity and Blender
- 微服務(wù)與事件驅(qū)動(dòng)架構(gòu)
- Hands-On Data Structures and Algorithms with JavaScript
- Java Web開發(fā)之道
- 華為HMS生態(tài)與應(yīng)用開發(fā)實(shí)戰(zhàn)
- 動(dòng)手玩轉(zhuǎn)Scratch3.0編程:人工智能科創(chuàng)教育指南
- Learning Firefox OS Application Development
- HTML5+CSS3網(wǎng)站設(shè)計(jì)基礎(chǔ)教程
- 零基礎(chǔ)輕松學(xué)SQL Server 2016
- 利用Python進(jìn)行數(shù)據(jù)分析(原書第3版)
- Python全棧數(shù)據(jù)工程師養(yǎng)成攻略(視頻講解版)
- Troubleshooting Citrix XenApp?
- Python函數(shù)式編程(第2版)