avatarFloriano Victor Peixoto

Summary

The web content introduces Rust's collection type, Vector, detailing its usage, features, and performance implications.

Abstract

The article "Rust Adventures: Introduction to Collections — Vector" delves into the concept of collections in Rust, focusing on the Vector structure. It explains the necessity of collections for managing groups of values, such as a list of student grades, and how Vectors in Rust provide a dynamic and safe alternative to fixed variables. The author illustrates how to create and manipulate Vectors, including adding and removing elements, and emphasizes Rust's safety features, such as the use of the Option enum to handle potential absence of values. The article also touches on the performance aspects of Vectors, discussing the difference between length and capacity, and how reaching the capacity limit triggers a performance-costly resize. The conclusion promises a follow-up article on HashMaps, reinforcing the importance of collections in programming and praising Rust's robust implementation.

Opinions

  • The author believes that Rust's Vector is a powerful tool for managing collections of data, superior to using fixed variables for each element.
  • Safety in Rust is highlighted as a key advantage, with mechanisms like the Option type preventing common errors such as NullPointerException and ArrayIndexOutOfBoundsException.
  • The article suggests that understanding the performance characteristics of Vectors, particularly the distinction between length and capacity, is crucial for optimizing system performance.
  • The author implies that Rust's collections are not only practical but also enjoyable to work with, indicating a positive experience with the language's features.
  • There is an appreciation for the Rust community and tools like criterion for benchmarking and understanding performance impacts.
  • The author encourages readers to explore Rust's collections further, hinting at the potential for more advanced use cases beyond the basics covered in the article.

Rust Adventures: Introduction to Collections — Vector

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.

Collections principal features

To make effective use of a collection you should be able to insert, update, delete and read values from it. Vector has an easy API to solve those questions.

Reading values from Vector

To read a value you can use a syntax like Java array [x] where x is the index.

This approach is prone to error because Vector doesn’t have a known size at compile time. You can pass a wrong index and the code will panic.

A much more safe way is to use the get(x)function that returns a Option. In Rust there is no null value. There won’t be any NullPointerException or ArrayIndexOutOfBoundsException in your code.

The Option says to us that can be no value in the index we just passed. When it occurs the return will be None, otherwise there will returns Some. This makes our code safer and more robust.

Inserting values into Vector

To include items you can use the push method. This will put at the end of the vector the passed value.

If the desired effect is to place a value in a specific index you should use insert(x,y). This will insert a value in the desired index and shift all next values to the right.

To add more than one value you can use extend_from_slice. Slices are read online variable containing a group of values. To create one you use the syntax &[] or use the & signal in front of a Vector.

Deleting values from Vector

Every collection needs to delete values in case that they are not needed anymore. Rust implemented in Vector a series of functions to this goal. The most basic are remove and remove_item. The first uses the value index and the second try to locate the first occurrence of the value and remove it. The remove_item is a just available in nightly-only experimental API.

In some computational problems you might want to unify the get and remove function. When you retrieve the value it will be removed from the collection. This function is called popand rust has it as well. popcollect the last item and removes it. It is used in LIFO problems.

The capacity of a collection

Collections in Rust has length and capacity. Length is about the values added to the collection and capacity is like rooms that the collections created to accommodate the values. Let’s see more about them.

About capacity and length

Every Vector is a triad of pointer, capacity and length. When you create a Vector with new method you have capacity 0 and length 0. When we use the vec! macro the capacity and length will be equal to the number of items.

Let’s think about performance

When you add more values to the Vector and it’s is reached the capacity the algorithm will increase it. This has a cost that can make your program slow.

So it’s important to think when performance is important to your system. Let’s use criterion to see how it can impact the performance of our code.

I runned the above code in criterion and found the following results:

It takes more time, but for most system it does not seems to impact performance. If you are working with critical performance systems, those milliseconds can make the difference.

You can find the project here.

Conclusion

So we covered the basic of Vectors, in the next article we’ll see more about HashMaps.

Collections are important for computational problems. In day-to-day of a programmer you’ll work a lot with them and rust ones is impressive.

I hope you all liked it and until next time!

If you like my work, please support it!♥

To understand how claps works, click here.

To contact me:

Technology
Programming
Software Development
Tech
Rust
Recommended from ReadMedium