What is the difference between tuples and array in rust?

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);

Destructuring arrays

Arrays can be destructured 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));

Destructuring tuples

Tuples can also be destructured and it's more common practise to destructure 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

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.

Tags:

Rust