AiViewz: Create and Share Your Content

Blogs, articles, opinions, and more. Your space to express and explore ideas.

Rust Programming Day 12: Collections- Vectors and Strings

In Day 12: Collections: Vectors and Strings of "Rusty Skills: Mastering Rust in 30 Days," you will explore two fundamental collections in Rust: vectors and strings. This article will guide you through the creation and manipulation of vectors, showcasing how to add, access, and iterate over elements. You will also learn about strings, including how to create, modify, and slice them, with an emphasis on Rust's support for UTF-8 encoding. Through a range of examples from basic to advanced, you'll gain a solid understanding of how to effectively use these collections to manage data in your Rust applications. Let’s dive in!

Objective

By the end of this lesson, you will understand how to use collections in Rust, focusing on vectors and strings. You will learn the basic operations, manipulation techniques, and advanced usage of these collections through a series of examples.


1. Introduction to Collections

In Rust, collections are used to store multiple values in a single data structure. Two commonly used collections are vectors (dynamic arrays) and strings. Vectors allow you to store a variable number of elements, while strings are used to handle text data.


2. Vectors: Creating and Manipulating

Basic Usage of Vectors

Vectors are defined using the Vec<T> type, where T represents the type of elements stored in the vector.

Example: Creating a Vector

fn main() {
    let mut numbers = Vec::new(); // Create a new, empty vector
    numbers.push(1);               // Add elements to the vector
    numbers.push(2);
    numbers.push(3);

    println!("{:?}", numbers); // Outputs: [1, 2, 3]
}

In this example, we create an empty vector and add three numbers to it using the push method.


3. Accessing and Modifying Vector Elements

You can access and modify elements in a vector using indexing.

Example: Accessing and Modifying Vector Elements

fn main() {
    let mut numbers = vec![10, 20, 30];
    
    // Access elements
    let first = numbers[0];
    println!("First element: {}", first); // Outputs: First element: 10

    // Modify an element
    numbers[1] = 25;
    println!("{:?}", numbers); // Outputs: [10, 25, 30]
}

In this example, we access the first element of the vector and modify the second element.


4. Iterating Over Vectors

You can iterate over the elements of a vector using a for loop.

Example: Iterating Over a Vector

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];

    for number in &numbers {
        println!("{}", number); // Outputs: 1 2 3 4 5
    }
}

In this example, we use a reference (&numbers) to avoid consuming the vector while iterating over it.


5. Advanced Example: Vectors of Structs

Vectors can also store custom data types, such as structs.

Example: Vectors of Structs

struct Student {
    name: String,
    grade: u32,
}

fn main() {
    let mut students: Vec<Student> = Vec::new();

    students.push(Student { name: String::from("Alice"), grade: 90 });
    students.push(Student { name: String::from("Bob"), grade: 85 });

    for student in &students {
        println!("{}: {}", student.name, student.grade);
    }
}

In this example, we define a Student struct and create a vector to store multiple Student instances. We then iterate through the vector to print each student's information.


6. Strings: Creating and Manipulating

Strings in Rust can be created using the String type or string literals (&str).

Example: Creating a String

fn main() {
    let mut greeting = String::from("Hello, ");
    greeting.push_str("World!"); // Append a string slice

    println!("{}", greeting); // Outputs: Hello, World!
}

In this example, we create a mutable String and use the push_str method to append additional text.


7. String Operations

You can perform various operations on strings, including indexing, slicing, and modifying.

Example: String Slicing

fn main() {
    let greeting = String::from("Hello, World!");
    let hello = &greeting[0..5]; // Slice the string

    println!("{}", hello); // Outputs: Hello
}

In this example, we slice the string to extract a portion of it.


8. Advanced Example: Working with UTF-8 Encoded Strings

Strings in Rust are UTF-8 encoded, which allows them to represent a wide range of characters.

Example: Iterating Over Characters in a String

fn main() {
    let greeting = String::from("Привет, мир!"); // Russian for "Hello, world!"

    for c in greeting.chars() {
        println!("{}", c); // Outputs each character
    }
}

In this example, we iterate over the characters in a UTF-8 encoded string and print each character, demonstrating Rust's support for international text.


9. Conclusion

In this lesson, you learned about collections in Rust, focusing on vectors and strings. You explored basic operations such as creating, modifying, and iterating over these collections, as well as advanced examples involving structs and UTF-8 encoded strings. Understanding these collections is essential for effective data handling in Rust.

Comments

Please log in to add a comment.

Back to Home
Join Our Newsletter

Stay updated with our latest insights and updates