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.
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.
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.
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);
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);
You can access element of tuple by tuple's name, dot, and index, ex:
let tup = (22, "str", 55);
assert_eq!(tup.0, 22);
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));
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: