Attempting to Figure Out Tuples and Arrays
In this video I try to use tuples and arrays, and in the end, emerge victorious.
Github repo: https://github.com/caveofprogramming/rust
Compound Types in Rust
Rust has two primitive compound (non-scalar) types: arrays, and tuples.
Arrays contain values of all the same type, whereas tuples can contain values of different types.
Both are fixed length.
While you can iterate over arrays, you can’t iterate over tuples.
Arrays
Creating arrays, changing or accessing values in arrays, printing arrays and looping over them, are all pretty straightforward if you’ve done this in any other language.
Note that the elements of the array cannot be changed unless you declare the array with mut
.
For the format specifier to println!
we need {:?}
, and we pass the variable as the second argument to the println!
macro.
You can declare the type of the array elements if you like.
The following declares an array containing 32-bit integers, with 2 elements.
Note the semi-colon in the type declaration.
You can also initialise an array with all the same element.
The following declares and initialises an array of 3 elements, which are all set to the value 7.
Again, note the semi-colon between the value of the elements (7) and the length of the array (3). If we put a comma there instead, we’d have an array containing two elements, 7 and 3.
Tuples
To create a tuple we use round brackets instead of square brackets as with an array.
To access elements in the tuple, we use a dot notation, following by an array-like subscript.
This code prints:
It’s possible to print a tuple only with a maximum of 12 elements.
In these examples I’ve created tuples of two elements, but a tuple can contain any number of elements.
We can declare an uninitialised tuple by declaring the types of its elements, but then we have to initialise it all in one go; Rust won’t let me then initialise the values separately before printing.
Here is my take. As you have mostly taught us Java, my impression is it seems a lot more "clunky" contrasted with Java. The syntax looks complex tbh. But we shall see which way this goes.
John did you ever study Fortran 77 when you started out at all? I studied it in 1987 at Staffordshire Poytechnic for my Geography degree. On that course we used a design methodology called Jackson Structured Design, which if this language is more procedural, may be more useful for Rust development?