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

From Script | Spoken-Tutorial
Jump to: navigation, search
Line 8: Line 8:
 
|| Welcome to the Spoken Tutorial on '''Borrowing in Rust.'''
 
|| Welcome to the Spoken Tutorial on '''Borrowing in Rust.'''
 
|-  
 
|-  
|| ''Slide 2'''
+
|| '''Slide 2'''
  
''Learning Objectives'''
+
'''Learning Objectives'''
 
|| In this tutorial, we will learn about:
 
|| In this tutorial, we will learn about:
 
* Borrowing and
 
* Borrowing and
Line 16: Line 16:
  
 
|-
 
|-
|| ''Slide 3'''
+
|| '''Slide 3'''
  
''System Requirements'''
+
'''System Requirements'''
 
|| To record this tutorial I’m using the follwoing setup
 
|| To record this tutorial I’m using the follwoing setup
 
|-  
 
|-  
 
|| '''Slide 4'''  
 
|| '''Slide 4'''  
  
''Code Files'''
+
'''Code Files'''
 
||
 
||
 
* The following code file is required to practise this tutorial.
 
* The following code file is required to practise this tutorial.
Line 29: Line 29:
  
 
|-  
 
|-  
|| ''Slide 5'''
+
|| '''Slide 5'''
  
''Borrowing'''
+
'''Borrowing'''
 
|| Let us learn about borrowing.
 
|| Let us learn about borrowing.
  
Line 39: Line 39:
  
 
|-  
 
|-  
|| ''Slide 6 '''
+
|| '''Slide 6 '''
  
''Borrowing - Example'''
+
'''Borrowing - Example'''
  
 
fn main() {
 
fn main() {
Line 198: Line 198:
 
|| Run the code to see the output.
 
|| Run the code to see the output.
 
|-  
 
|-  
|| ''Slide 10'''
+
|| '''Slide 10'''
  
''Rules of Borrowing:  Rule 3'''
+
'''Rules of Borrowing:  Rule 3'''
  
 
|| You cannot mix''' mutable '''and''' immutable references '''to the same data at the same time.
 
|| You cannot mix''' mutable '''and''' immutable references '''to the same data at the same time.
Line 311: Line 311:
 
Let us summarize.  
 
Let us summarize.  
 
|-  
 
|-  
|| ''Slide  12''
+
|| '''Slide  12''
  
''Assignment'''
+
'''Assignment'''
  
 
''fn main() {'''
 
''fn main() {'''
Line 331: Line 331:
  
 
|-  
 
|-  
|| ''Slide 9 '''
+
|| '''Slide 13 '''
  
 
''Thank You'''
 
''Thank You'''

Revision as of 16:55, 7 October 2025

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

Learning Objectives

In this tutorial, we will learn about:
  • Borrowing and
  • Rules of borrowing
Slide 3

System Requirements

To record this tutorial I’m using the follwoing 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

Borrowing

Let us learn about borrowing.
  • Borrowing is the act of creating references to data without taking ownership
  • When we borrow a value, we reference its memory address with the &


Slide 6

Borrowing - Example

fn main() {

let s = String::from("hello");

let s1 = &s;

}

  • Here ‘s’ owns the string “hello
  • s1’ borrows ‘s’ by reference denoted by &s.

But ownership of the string is still with s.

  • s1 is only allowed to read the data
  • It will point to the data, making it an immutable reference to s.
Next we will see about rules of borrowing.
Slide 7

Rules of borrowing: Rule 1

1. Any number of Immutable references to a data

  • You can have any number of immutable references to a data at the same time.
  • Immutable references do not allow modification of the data.
Slide 8

Rules of borrowing: Rule 1

  • Any number of read operations are safe, but write operations are not allowed.
Let us understand with an example.
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 borrow

In the menu bar, File >> Open folder

>> Desktop >> MyRustProject >> borrow

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

Type the command cargo new borrow 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 a = String::from("Hello world");

let b = &a;

let c = &a;

let d = &a;

println!("{}", b);

println!("{}", c);

println!("{}", d);

}

Variables b, c, d are assigned with an immutable reference to a.

When you try to print them, there won't be any errors.

It allows multiple immutable references to a piece of data simultaneously.

Save the program.

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

Output shows, variable a can have multiple immutable references.

Slide 9

Rules of borrowing: Rule 2

2. Only 1 mutable reference to a data

The second rule states that you can have only one mutable reference to a data.
Let us see an example.

Clear the previous code. Copy paste the code from the Code file.

fn main() {

let mut s = String::from("Hello ");

let r1 = &mut s;

let r2 = &mut s;

r1.push_str("World"); r2.push_str("Rust");

println!("{}",r1);

println!("{}",r2);

}

Here, the mutable variable s is assigned to a string object hello.

Variables r1, r2 are assigned with a mutable reference to s.

When both the references try to modify the data, rust wont allow this.

It will lead to a data race, where the data gets corrupted.

fn main() {

let mut s = String::from("Hello ");

let r1 = &mut s;

//let r2 = &mut s;

r1.push_str("world");

//r2.push_str("Rust");

println!("{}",r1);

//println!("{}",r2);'

}

Run the code and check the error.

Let us comment the code, related to the second mutable reference.

Save the program.

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

Rules of Borrowing: Rule 3

You cannot mix mutable and immutable references to the same data at the same time.
Let us understand through an example.

Copy and paste the code from the Code file.

fn main() {

let mut s = String::from("Hello ");

let r1 = &mut s;

// let r2 = &s;

r1.push_str("Rust");

println!("{}", r1);

}

Mutable variable s is assigned to a string object hello.

Here r1 is assigned ;">as a mutable reference to s.

">And;"> r2 ;">as ;">an immutable reference to s

One reference tries to modify the data while another reference tries to read data.

It will lead to corrupt data because the reference didn’t get out of scope.

It still has the mutable reference and may change the data in the scope.

Comment the line of immutable reference to s;"> ;">as shown.

Save the program.

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

Hence rust doesn't allow you to break all the above 3 rules.

Next we will see how dangling references occur and how Rust prevents them.
Let us understand with an example.
Copy and paste the code from the code file.
fn get_reference() -> &String {

let s = String::from("Hello, Rust!");

&s // ❌ Error: `s` is dropped at the end of this function

} // `s` goes out of scope here, but we're trying to return a reference to it

fn main() {

let r = get_reference(); // Trying to use a reference to `s`, but `s` is already dropped

println!("{}", r);

}

Inside get_reference(), we create a String named s.

In the next line, it returns a reference to that string.

When the function ends, s goes out of scope, and its heap memory is freed.

Here we are trying to return a reference to this freed memory.

Hence, we will get an error.

When we try to run the main function, it leads to an invalid memory.( a dangling reference).

Save the program.

In the terminal, type cargo run . Let us run the program and check the error.
fn get_reference() -> String {'

let s = String::from("Hello, Rust!");'

s // ownership is moved out safely'

} '

Let's see how to correct this program?

Let us modify the program to return a value not the reference.

Remove the & from s.

Save the program.

In the terminal, type cargo run . Now run the program and see the result.
Slide 11
  • Borrowing
  • Rules of borrowing
This brings us to the end of this tutorial.

Let us summarize.

'Slide 12

Assignment

fn main() {'

let fruit1 = String::from("Apple");'

let fruit2 = fruit1; '

println!("fruit1 = {}", fruit1); '

println!("fruit2 = {}", fruit2);'

}'

As an assignment,

Run the above code and fix the error.

Slide 13

Thank You'

Thank you for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat