Rust-Programming-Language/C2/Ownership/English

From Script | Spoken-Tutorial
Jump to: navigation, search
Visual Cue Narration
Slide 1 Welcome to the Spoken Tutorial on Ownership in Rust.
Slide 2

Learning Objectives

In this tutorial, we will learn about:
  • Ownership
  • Ownership Rules
  • Drop and Copy traits
Slide 3

System Requirements

To record this tutorial I am using:
  • Ubuntu Linux OS version 22.04
  • Rust version 1.80.0
  • Visual Studio Code version 1.19.0
Slide 4

Prerequisites

To follow this tutorial, you should be familiar with compiling and running a Rust program.
Slide 5

Code Files

  • The following code file is required to practise this tutorial.
  • Ownership.rs
  • This file is provided in theCode Files link of this tutorial page.
Slide 6

Ownership

Let us now learn about Ownership.
  • Ownership allows memory safety without a garbage collector.
  • It is a key feature of Rust language that allows it to be both safe and fast.
Slide 7

Ownership Rules

  • Each value in Rust has a single owner
  • There can be only one owner at a time
  • When the owner goes out of scope the value will be dropped.
Slide 8

Drop trait

  • To understand the ownership rules, we need to note two traits:
  • drop and copy
  • These traits are fundamental traits related to resource management and memory handling.
Let us understand the drop trait through an example.
Open'Visual'code editor Open theVisual Studio code editor.
In the menu bar, click onTerminal and select New Terminal. In the menu bar, click onTerminal and select New Terminal.
> cd'Desktop'/MyRustProject

'>'cargo newOwnership

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

>> MyRustProject >> Ownership

Let us go to our working directoryMyRustProject as explained earlier.

Type the command cargo new Ownership and pressEnter.

Open the created project as shown.

Point to themain.rs file. In themain.rs file, copy and paste the code from theCode file.
struct MyStruct {

data: String,

}

//highlight impl Drop for MyStruct

impl Drop for MyStruct {

fn drop(&mut self) {

println!("Dropping MyStruct with data: {}", self.data);

}

}

fn main() {

println!("Start");

{

let new_struct = MyStruct {

data: String::from("Hello, world!"),

};

}

println!("End");

// my_struct goes out of scope here, and the drop method is called.

}

This code explains how ownership and Drop trait work together in Rust.

Here wecreated a'struct'MyStruct which contains data ofstring type.

In the implementation block,the drop trait forMystruct has been implemented.

The drop method is automatically called when an object goes out of scope.

In the main program,new_struct is created with "Hello, world!" stored in its data.

Here,new_structowns that string.

At the end of the inner scope,new_struct goes out of scope.

Rust automatically callsdrop(&mut self) fornew_struct.

In this code, drop happens before "End" is printed.

This is because the struct’s scope ends earlier.

Save the program.

Type cargo run. Run the code to see the output.
Next, let us see an example of a copy trait.

Clear the code window and copy paste the code from theCode file.

fn main() {

let x = 10;

let y = x; // x is copied, not moved

println!("x: {}, y: {}", x, y); // x is still accessible

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

letv = s; // Move occurs, `s` is no longer valid

// println!("{}", s); // This would cause an error

}

Here, x is assigned a value 10, and y is assigned to variable x.

For simple types like i32, boolean, char, etc., Rustcopies the value instead of moving it.

These data types are entirely stored on the stack.

It has a fixed size known at compile time.

After copying, both x and y hold the value 10.

But for the string, the variable s is assigned the value “Hello World!”.

Variable v is assigned to s.

Here,copy doesn’t happen because of String being an owned type.

This fails because after the move,s no longer owns any valid data.

Rust’s compiler prevents you from using s here.

Hence it would show an error.

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

We can see the copy trait is implemented by default forinteger.

For string type we get an error.

Types likeString or other heap-allocated structures do not implement Copy by default.

let t = s.clone(); // deep copy of the string data

println!("s: {},v: {}", s,v); // both accessible

We can use the clone method to solve this issue.

Let's add the clone method as s.clone() in the code.

.clone() method makes an explicit deep copy of the heap data.

Change the print statement to print s and v.

Save the program.

Run the code to see the correct output.
Slide 9

Summary

This brings us to the end of this tutorial.

Let us summarize.

Slide10

Assignment

As an assignment. write a program that:
  • Creates a String variable called greeting with the value "Hello, Rust!".
  • Passes it to a function takes_ownership that prints the value.
  • Inside this function, remember that ownership is moved.
Slide11

Thank You

Thank you for joining

Contributors and Content Editors

Madhurig, Nirmala Venkat