In this lesson we take a look at Arrays and the different ways of creating them. Arrays in Rust are collections of values of the same type that cannot change in size. In other words, the number of fields (or elements) has to be known at compile time.
Pascal Precht: [0:00] Unlike in many other languages, arrays in Rust are a collection of values of the same type that cannot change in size. We create them by writing a separated list of values, as we can see here with the names, surrounded by brackets.
[0:14] Down here, we're iterating over the names and simply output them one by one. If I run this program, we can see that it outputs Pascal, Christoph, and Elvira.
[0:23] The type used in arrays can also be explicitly set using annotations. For example, if we create a list of numbers which indeed holds a bunch of numbers, Rust will, in this case, use the type i32 because these are all integers and there's no explicit type given. If we wanted to make this explicit, we would give it i32 here and then the number of fields, which is 4.
[0:49] The same way, we can also change the type here. Let's say we want to go with an i8 instead. Then, changing names to numbers here, and let's call this number instead, we will see that Rust will output all the numbers one by one.
[1:05] Another way to create an array is to specify the value and the number of fields that the array will prefill. For example, we could say zeros is an array of zeros with 1,024 fields. This is now an array of 1,024 zeros.
[1:25] Using this technique is very useful when we want to create fixed-size buffers. For example, we could say this is a kilobyte. Then we typecast the zeros to u8, which make the fields unsigned 8-bit integers.
This needs a blog post. I'll put one together and post it here once done.
Is the blog up? I have the same question.
Hey Anthony,
unfortunately I didn't get to writing it yet. Life happened, ha. But thanks for the reminder!
hi Pascal, is the blog finished ? is that &names for leaving the ownership in the array ? or it is for performance ?
Why did you use a reference to the array?
When I try it without the ampersand, I get a compile error that the array is not an iterator.