Hi there folks! Let’s continue our journey over Rust lands.

Today we are going to cover Collections. It is a central aspect of every programming language.

But what are collections?

In a previous article, we discussed the Rust ownership and variable values. Variables are memory locations where our values are stored. If you want to make a simple program to calculate the mean of a student’s notes.

Assuming that we have three students let’s code a little:

That seems to be OK, but what in the middle of the year a new student comes into class? We could always put one more variable, but the number of students can increase a lot and that will not be reasonable. If someone asks us to order the values? The problems sum up as we increase the demands for new features, so what now?

Collections to the rescue

Collections solve this problem by reserving a space in memory to put groups of values. Instead of creating one fixed variable for each student, we can create a group of students.

The basic structure Rust has to do that is Vector. So our program will change to create this structure.

If you want to create it with initial values use the vec! macro:

Or we could make it with initial zero value and add the values later. We need to declare it mutable.

Now to calculate the mean we could use the Iterator trait. It contains various methods to process values in a collection.

Now we can play with the values as much as we want without too much effort.

#software-development #programming #tech #rust #technology

Rust Adventures: Introduction to Collections — Vector
1.05 GEEK