Learn how to represent multiple values of different type using a single type by leveraging the power of tuples in Rust.
Another interesting type. This seems functionally similar to any[]
in TypeScript, only with a maximum length. Is tuple the only option in Rust for an array-like of mixed types? Short of creating your own custom types, I mean.
Tuples can hold up to 12 values.
I'm confused about this. I tried creating a tuple bigger than that just to see what would happen:
let tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
println!("14th value: {}", tuple.13);
It still works.
let (head, tail) = text.split_at(5);
I appreciate that Rust allows this kind of destructuring syntax, as opposed to requiring something like this:
let split = text.split_at(5);
let head = split.0;
let tail = split.1;
This seems functionally similar to any[] in TypeScript, only with a maximum length.
Not exactly, because any[]
doesn't dictate the order of types in use while a tuple (e.g. (i32, &str, String)
) does.
Is tuple the only option in Rust for an array-like of mixed types?
I think so. There are other collection types like HashMap<K, V>
, where K
and V
can be of different type, this of course also has different semantics.
I'm confused about this. I tried creating a tuple bigger than that just to see what would happen:
To be honest, I trusted the number I've read in my book and never verified it myself. Very good catch! Will update this episode accordingly!!
Say I update part of a tuple with new values. Must the type order remain the same?
Hey Anthony,
yes, the order has to remain the same otherwise you'd actually change the type of value. So for example:
let mut point = ("A", 8, 9); // (&str, i32, i32) <- this is the current type
point.0 = "B"; // <- this works fine as `point` is mutable and `point.0` is of type `&str`
point.0 = 3; // <- this will be a compilation error because the expected type of `point.0` is `&str` (per initialization)
Makes sense! Thanks, Pascal!
Great courses so far! They are to the point and pack a lot of information. I appreciate your style.
I have learnt a lot!