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.
In this article we also talk about tuples and arrays. Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly.
A tuple is a collection of values of different types. Tuples are constructed using parentheses () , and each tuple itself is a value with type signature (T1, T2, ...) , where T1 , T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values.
In Rust, a tuple is immutable, which means we cannot change its elements once it is created. However, we can create a mutable array by using the mut keyword before assigning it to a variable. For example, // create a mutable array let mut mountains = ("Everest", 8848, "Fishtail", 6993);
In Rust, arrays are created using square brackets [] and their size needs to be known at compile time. An array whose size is not defined is called a slice.
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 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);
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 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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With