learn-rust

Free Rust 🦀 course in English 🇬🇧

View on GitHub

Table of Contents📚

Vectors

What is a vector❔

A vector is a data structure that can store a collection of data of the same type.

Declaring a vector

To declare an empty vector, use the Vec<T> type, where T is the type of the elements in the vector.

let mut string_vec: Vec<String> = Vec::new();

ℹ️ We have to make the vector mutable to be able change its elements.

ℹ️ We use the Vec::new() method to create an empty vector.

Declaring a vector with elements

Declaring a vector with default values is much easier.

And we don’t need to specify the type of the elements.

let mut string_vec = vec!["Hello", "World"];

ℹ️ We use the vec! macro to create a vector with the given elements.

Accessing elements

let mut string_vec = vec!["Hello", "World"];
println!("{} 👋", string_vec[0]);

ℹ️ We use the [] operator to access the element at the given index.

Output:

Hello 👋

Joining elements

To join the elements of a vector with a specific separator, we can use the join method.

let mut string_vec = vec!["Hello", "World"];
println!("{}", string_vec.join("!"));
println!("{}", string_vec.join("->"));
println!("{}", string_vec.join(" "));

Output:

Hello!World
Hello->World
Hello World

Pushing elements

We can push elements to the end of the vector using the push method.

let mut string_vec = vec!["I", "Love"];

string_vec.push("Rust");

println!("{} 💖", string_vec.join(" "));

Output:

I Love Rust 💖

Removing elements

We can remove an element with its index using the remove method.

let mut string_vec = vec!["I", "Love", "Rust"];

string_vec.remove(1);

println!("{} 💖", string_vec.join(" "));

Output:

I Rust 💖

Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode