Difference between revisions of "Rust-Programming-Language/C2/Collections/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 22: Line 22:
  
 
|-  
 
|-  
|| '''Slide''' '''4'''
+
|| '''Slide 4'''
  
 
'''Code Files'''
 
'''Code Files'''
Line 30: Line 30:
  
 
|-  
 
|-  
|| '''Slide 6:'''
+
|| '''Slide 5'''
  
 
'''Collections'''
 
'''Collections'''
 
|| Let us get started.
 
|| Let us get started.
 +
 
* '''Collections''' are data structures that hold multiple values together
 
* '''Collections''' are data structures that hold multiple values together
 
* They are used to store, retrieve, and manipulate groups of related values efficiently.
 
* They are used to store, retrieve, and manipulate groups of related values efficiently.
 
* Rust's collection types are available in the '''std::collections''' module  
 
* Rust's collection types are available in the '''std::collections''' module  
 
|-  
 
|-  
|| '''Slide7:'''
+
|| '''Slide 6'''
  
 
'''Types of Collections'''
 
'''Types of Collections'''
Line 55: Line 56:
 
|| In the menu bar, click on '''Terminal''' and select''' New Terminal'''.
 
|| In the menu bar, click on '''Terminal''' and select''' New Terminal'''.
  
|| In the menu bar, click on '''Terminal''' and select''' New Terminal'''.
+
|| In the menu bar, click on '''Terminal''' and select ''' New Terminal'''.
  
 
|-  
 
|-  
Line 67: Line 68:
 
|| Let us go to our working directory '''MyRustProject''' as explained earlier.
 
|| Let us go to our working directory '''MyRustProject''' as explained earlier.
  
Type the command '''cargo new collections '''and press '''Enter.'''
+
Type the command '''cargo new collections ''' and press '''Enter.'''
  
 
Open the created project as shown.
 
Open the created project as shown.
 
|-  
 
|-  
 
|| Point to the '''main.rs''' file.
 
|| Point to the '''main.rs''' file.
 
 
|| In the '''main.rs '''file, copy and paste the code from the Code file.
 
|| In the '''main.rs '''file, copy and paste the code from the Code file.
 
|-  
 
|-  
Line 108: Line 108:
 
We declare a '''mutable vector''' called '''fruits''' and it is initialized with "Apple".
 
We declare a '''mutable vector''' called '''fruits''' and it is initialized with "Apple".
  
push() is a method to add elements to the end of the vector.
+
push() method is a method to add elements to the end of the vector.
  
 
We add '''banana''' and '''cherry''' to the second and third position using the '''push''' method.
 
We add '''banana''' and '''cherry''' to the second and third position using the '''push''' method.
Line 114: Line 114:
 
We use the '''get() '''method which returns an '''Option enum'''.
 
We use the '''get() '''method which returns an '''Option enum'''.
  
'''fruits.get(1) '''accesses the element at index 1 and prints '''Some(“Banana”)'''
+
'''fruits.get(1) ''' method accesses the element at index 1 and prints '''Some(“Banana”)''' method.
  
'''fruits.get(5) '''is an invalid index and so it prints '''None.'''
+
'''fruits.get(5) ''' method is an invalid index and so it prints '''None.'''
  
 
.pop() method removes the last element from the vector.
 
.pop() method removes the last element from the vector.
  
In our case, "Cherry" is the last item and it gets removed..is_empty() checks if the vector has zero elements..len() returns the number of elements present in the vector.Save the program.
+
In our case, "Cherry" is the last item and it gets removed.
 +
 
 +
.is_empty() checks if the vector has zero elements.
 +
 
 +
.len() returns the number of elements present in the vector.
 +
 
 +
Save the program.
 
|-  
 
|-  
||  
+
|| Type cargo run.
 
|| Run the code to see the output.
 
|| Run the code to see the output.
  
is_empty() returns false since the vector is not empty.
+
is_empty() method returns false since the vector is not empty.
  
 
The vector has 2 elements and so the '''len''' method prints,
 
The vector has 2 elements and so the '''len''' method prints,
Line 165: Line 171:
 
|| Copy paste the code from the Code file.
 
|| Copy paste the code from the Code file.
  
In Rust, '''HashMap''' is not available by default.We need to '''import '''it from the std::collections module to use it.
+
In Rust, '''HashMap''' is not available by default.
  
We create a '''new, empty''', and '''mutable''' '''HashMap''' called '''capitals'''.
+
We need to '''import '''it from the std::collections module to use it.
 +
 
 +
We create a '''new, empty''', and '''mutable HashMap''' called '''capitals'''.
  
 
insert() method allows us to store a '''key''' with its value.
 
insert() method allows us to store a '''key''' with its value.
  
The keys are the country names and the values are their capitals
+
The keys are the country names and the values are their capitals.
  
 
Similar to Vector, we use the '''.get()''' method, to retrieve the value for a given key.
 
Similar to Vector, we use the '''.get()''' method, to retrieve the value for a given key.
Line 189: Line 197:
 
Save the program.
 
Save the program.
 
|-  
 
|-  
||  
+
|| type cargo run
 
|| Run the program to see the output.
 
|| Run the program to see the output.
 
|-  
 
|-  
Line 195: Line 203:
 
|| Next we will see about '''Hashset'''.
 
|| Next we will see about '''Hashset'''.
 
|-  
 
|-  
|| Slide:
+
|| '''Slide 7'''
 
+
Hashset:
+
'''Hashset'''
 
||
 
||
 
* It is a collection of unique values.
 
* It is a collection of unique values.
Line 205: Line 213:
 
|-  
 
|-  
 
||  
 
||  
|| Switch back to the visual code editor.
+
|| Switch back to the '''visual code editor'''.
  
 
Copy paste the code from the Code file.
 
Copy paste the code from the Code file.
Line 238: Line 246:
  
 
    println!("Number of persons: {}", names.len());
 
    println!("Number of persons: {}", names.len());
|| In this code, we create a '''mutable''' empty HashSet, called '''names.'''
+
 
 +
|| We create a '''mutable''' empty HashSet, called '''names.'''
  
 
'''.insert()''' method insert elements to the '''HashSet'''.
 
'''.insert()''' method insert elements to the '''HashSet'''.
Line 245: Line 254:
  
  
Hash sets only store unique items.
+
'''Hash''' sets only store unique items.
  
 
The .contains() method checks if a specific '''item '''is present inside the '''HashSet'''.
 
The .contains() method checks if a specific '''item '''is present inside the '''HashSet'''.
Line 259: Line 268:
 
Save the program.
 
Save the program.
 
|-  
 
|-  
||  
+
|| In the terminal, type '''cargo run '''
|| In the terminal, type '''cargo run '''and see the output.
+
|| In the terminal, type '''cargo run ''' and see the output.
 
|-  
 
|-  
||  
+
||'''Slide 8'''
 +
 
 +
'''Summary'''
 
|| This brings us to the end of this tutorial.
 
|| This brings us to the end of this tutorial.
  
 
Let us summarize.  
 
Let us summarize.  
 
|-  
 
|-  
|| '''Slide 8'''
+
|| '''Slide 9'''
  
 
|| As an assignment,
 
|| As an assignment,
Line 273: Line 284:
 
Write a Rust program that:
 
Write a Rust program that:
 
# Takes a list of numbers  
 
# Takes a list of numbers  
# Uses a HashSet to find all the '''unique numbers'''.
+
# Uses a HashSet to find all the unique numbers.
  
 
|-  
 
|-  
|| '''Slide 9 '''
+
|| '''Slide 10 '''
  
 
'''Thank You'''
 
'''Thank You'''

Latest revision as of 14:06, 11 October 2025

Visual Cue Narration
Slide 1 Welcome to the Spoken Tutorial on Collections in Rust.
Slide 2

Learning Objectives

In this tutorial, we will learn about:
  • Collections and
  • Types of Collections
Slide 3

System Requirements

  • To record this tutorial I’m using the following setup.
Slide 4

Code Files

  • The following code file is required to practise this tutorial.
  • This file is provided in the Code Files link of this tutorial page.
Slide 5

Collections

Let us get started.
  • Collections are data structures that hold multiple values together
  • They are used to store, retrieve, and manipulate groups of related values efficiently.
  • Rust's collection types are available in the std::collections module
Slide 6

Types of Collections

Rust has 3 common collections that are used very often.
  • Vectors are dynamic arrays that can grow or shrink in size as needed.


  • Hash Map is a key-value pair storage for fast lookups by key
  • HashSet is a collection of unique items with no duplicates
Open Visual code editor Open the Visual Studio code editor.
In the menu bar, click on Terminal and select New Terminal. In the menu bar, click on Terminal and select New Terminal.
> cd Desktop/MyRustProject

> cargo new collections

In the menu bar, File >> Open folder >>

Desktop >> MyRustProject >> collections

Let us go to our working directory MyRustProject as explained earlier.

Type the command cargo new collections and press Enter.

Open the created project as shown.

Point to the main.rs file. In the main.rs file, copy and paste the code from the Code file.
fn main() {

let mut fruits = vec!["Apple"];

fruits.push("Banana");

fruits.push("Cherry");

// Accessing elements safely

println!("{:?}", fruits.get(1)); // Some("Banana")

println!("{:?}", fruits.get(5)); // None

// Removing last element

fruits.pop();

println!("{:?}", fruits); // ["Apple", "Banana"]

// Checking if empty

println!("{}", fruits.is_empty());

// Checking length

println!("Number of fruits: {}", fruits.len());

}

This code explains how the vector works.

We declare a mutable vector called fruits and it is initialized with "Apple".

push() method is a method to add elements to the end of the vector.

We add banana and cherry to the second and third position using the push method.

We use the get() method which returns an Option enum.

fruits.get(1) method accesses the element at index 1 and prints Some(“Banana”) method.

fruits.get(5) method is an invalid index and so it prints None.

.pop() method removes the last element from the vector.

In our case, "Cherry" is the last item and it gets removed.

.is_empty() checks if the vector has zero elements.

.len() returns the number of elements present in the vector.

Save the program.

Type cargo run. Run the code to see the output.

is_empty() method returns false since the vector is not empty.

The vector has 2 elements and so the len method prints,

Number of fruits as 2.

Next we will see about HashMap.
use std::collections::HashMap;

fn main() {

let mut capitals = HashMap::new();

// Insert key-value pairs

capitals.insert("India", "New Delhi");

capitals.insert("USA", "Washington D.C.");

// Accessing elements

println!("{:?}", capitals.get("India"));  // Some("New Delhi")

println!("{:?}", capitals.get("France")); // None

// Removing an entry

capitals.remove("USA");

// Checking if key exists

if capitals.contains_key("India") {

println!("Found India's capital!");

}

Copy paste the code from the Code file.

In Rust, HashMap is not available by default.

We need to import it from the std::collections module to use it.

We create a new, empty, and mutable HashMap called capitals.

insert() method allows us to store a key with its value.

The keys are the country names and the values are their capitals.

Similar to Vector, we use the .get() method, to retrieve the value for a given key.

If the key exists, it returns Some(value).

If the key does not exist, it returns None.

The remove() method deletes the entry with the given key.

It removes "USA" and its capital "Washington D.C." from the HashMap.

The contains_key() method checks if a specific key is present inside the HashMap.

The len() method gives the total number of key-value pairs present inside the HashMap.

Save the program.

type cargo run Run the program to see the output.
Next we will see about Hashset.
Slide 7

Hashset

  • It is a collection of unique values.
  • It does not store duplicate entries, that is no two identical items can exist in it.
  • It is unordered — The elements do not have a guaranteed order inside the set.
Switch back to the visual code editor.

Copy paste the code from the Code file.

use std::collections::HashSet;

fn main() {

let mut names = HashSet::new();

// Inserting elements

names.insert("Jack");

names.insert("Joe");

names.insert("Jill");

names.insert("Joe"); // Duplicate, will be ignored

    if names.contains("Joe") {

        println!("Joe is present!");

    }

    // Removing an element

names.remove("Jill");

    // Checking length

    println!("Number of persons: {}", names.len());

We create a mutable empty HashSet, called names.

.insert() method insert elements to the HashSet.

When we try to insert the name Joe twice, the second insertion is ignored automatically.


Hash sets only store unique items.

The .contains() method checks if a specific item is present inside the HashSet.

It will print a success message if the name joe exists.

The remove() method deletes a specific value from the set.

We can also loop through all the elements and print them.

The order is not guaranteed because HashSets are unordered.

Save the program.

In the terminal, type cargo run In the terminal, type cargo run and see the output.
Slide 8

Summary

This brings us to the end of this tutorial.

Let us summarize.

Slide 9 As an assignment,

Write a Rust program that:

  1. Takes a list of numbers
  2. Uses a HashSet to find all the unique numbers.
Slide 10

Thank You

Thanks for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat