- 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.
推薦閱讀
- Django+Vue.js商城項目實戰
- JavaScript修煉之道
- Python自然語言處理實戰:核心技術與算法
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- 算法基礎:打開程序設計之門
- Responsive Web Design by Example
- 零基礎學單片機C語言程序設計
- NoSQL數據庫原理
- 新一代SDN:VMware NSX 網絡原理與實踐
- HTML5秘籍(第2版)
- 零基礎學Kotlin之Android項目開發實戰
- 時空數據建模及其應用
- Django 3.0應用開發詳解
- 軟件測試分析與實踐
- Learning WordPress REST API