官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 上栗县| 德江县| 馆陶县| 桐庐县| 景东| 马龙县| 饶阳县| 双桥区| 永春县| 三原县| 含山县| 中宁县| 金湖县| 罗田县| 客服| 昌乐县| 湛江市| 广宁县| 都江堰市| 深州市| 驻马店市| 道孚县| 甘德县| 阳原县| 东乌珠穆沁旗| 平江县| 铜鼓县| 洛宁县| 诸暨市| 同江市| 兰溪市| 庄浪县| 孝昌县| 长春市| 玉树县| 荆门市| 临泉县| 泽普县| 昌乐县| 斗六市| 许昌市|