What is the difference between tuples and array in

2019-07-17 11:08发布

问题:

The only real difference I can figure out after reading the beginner guide, is that in tuple you can have values of multiple types? Both are immutable?

And what are the use cases where I'd want a tuple or array, apart from the obvious one.

回答1:

An array is a list of items of homogeneous type. You can iterate over it and index or slice it with dynamic indices. It should be used for homegeneous collections of items that play the same role in the code. In general, you will iterate over an array at least once in your code.

A tuple is a fixed-length agglomeration of heterogeneous items. It should be thought of as a struct with anonymous fields. The fields generally have different meaning in the code, and you can't iterate over it.



回答2:

Array

  • collection of values of the same type
  • fixed-sized collection

Accessing element

You can access element of array by array's name, square brackets, and index, ex:

let arr = [22, 433, 55];
assert_eq!(arr[0], 22);

Destructing array

Arrays can be destructed into multiple variables, ex:

let arr = [1, 42 ,309];
let [id, code, set] = arr;

assert_eq!(id, 1);
assert_eq!(code, 42);
assert_eq!(set, 309);

Tuple

  • collection of values of different types
  • finite heterogeneous sequence

Accessing element

You can access element of tuple by tuple's name, dot, and index, ex:

let tup = (22, "str", 55);
assert_eq!(tup.0, 22);

Functions

Tuples may be used to return multiple values from functions, ex:

fn num(i: u32) -> (i64, u32) {
    (-33, 33 + i)
}

assert_eq!(num(12), (-33, 45));

Destructing tuples

Tuples can also be destructed and it's more common practise to destruct tuples rather than arrays, ex:

let tup = (212, "Wow", 55);
let (num, word, id) = tup;

assert_eq!(num, 212);
assert_eq!(word, "Wow");
assert_eq!(id, 55);

Useful resources:

  • Compound Types - The Rust Programming Language
  • Tuples - Rust by example
  • Arrays and Slices - Rust by example


标签: rust