Rust/C2/Data-Types-in-Rust/English

From Script | Spoken-Tutorial
Revision as of 11:18, 21 June 2021 by Nancyvarkey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of the script: Data Types

Author: Jayesh Katta Ramalingaiah

Domain Reviewer: Vigneshwer Dhinakaran

Novice Reviewer: Praveen S.

Keywords: Rust, variables, data types, scalar, integers, float, boolean, character


Visual Cue
Narration
Slide: Title Welcome to the spoken tutorial on “Data Types in Rust”.
Slide:

Learning Objectives

In this tutorial, we will learn about:
  • Supported Data Types
  • Scalar Data Types
  • Compound Data Types and
  • Its types in Rust.
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Rust version 1.47.0
  • Visual Studio Code version 1.45.0 (code editor)

However you may use any other editor of your choice.

Slide : Pre-requisites To practice this tutorial,
  • You should be familiar with compiling and running Rust files.
  • If not, please go through the prerequisite Rust tutorials on this website.
Slide: Code files
  • The file used in this tutorial is available in the Code files link on this tutorial page.
  • Pls download and extract the file.
  • Make a copy and then use it for practising.
Slide: Data Types in Rust
  • Every value in Rust is of a certain Type.
  • It tells the compiler what kind of data is being specified.
  • This helps the compiler know how to work with that data.
  • And, helps optimize for efficient & faster runtime execution.
  • There are a number of in-built Data Types in Rust.

We’ll see them now.

Slide: Data Types in Rust There are 2 major data types namely scalar and compound.
[Only narration] Do remember that Rust is a statically typed language.


That means it checks what are the types of variables at compile time.


The compiler can usually infer what data type is used based on the value and improve runtime efficiency.

Slide: Scalar Types
  • A Scalar Data Type represents a single value.
  • Rust has four primary scalar data types
    • Integers
    • Float
    • Boolean
    • Character

Now let us take an example of a scalar data type and see how it works in Rust.

Press Ctrl+Alt+T keys Open the terminal by pressing Ctrl,Alt and T keys simultaneously on the keyboard.


Ensure that you have root permissions to run the commands.

Only Narration Here onwards, please remember to press the Enter key after typing each command.
[Terminal] Type:


cd Desktop/MyRustProject

[Enter]

Using cd command go to the Rust practice folder which we created earlier.
[Terminal] Type:


cargo new scalar_types [Enter]

Let us create a new project named scalar_types.


Type the command as shown.

Open Visual Studio Code editor. You may use any editor of your choice.


I will use Visual Studio Code editor for this demonstration.

[Editor]


Welcome Page ->

Open Folder ->

scalar_types

Open the created project by clicking on the Open folder link in the Welcome page.


Browse and locate the folder “scalar_types”.


Then click on the Open button at the top right corner.

[Editor]

Click on scalar_types

Under the EXPLORER section, expand the project folder “scalar_types” by clicking on it.
[Editor] Expand src and click on main.rs Then expand src and then open main.rs file.
[Editor] Type:


fn main() {

let mut a = 2147483647;

a = a + 1;

print!(“The value of a is {}”,a);

}

In the editor, replace the code as shown.
[Editor] Highlight:

let mut a = 2147483647;

Here the variable a is declared with value 2147483647, which is an integer variable.


By default, the integer variable is 32-bit (i32), which is a signed integer type and can hold both +ve and -ve values.


Rust even offers unsigned integers type.


You can explicitly typecast to u32 if you don’t want the value to go below zero.


So the maximum value it can take is 2147483647 which is equal to 2 power 32 minus 1 .

[Editor] Highlight:


a = a + 1;

Next we are experimenting by trying to add 1 to the maximum value.
[Editor] Highlight:


print!("The value of a is {}",a);

Using the print method we are printing the variable’s value.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cd scalar_types [Enter]

Go to the project folder scalar_types using the cd command.
[Terminal] Type:


cargo run [Enter]

Now type cargo run
[Terminal] Highlight:


attempt to add with overflow

Here, we see an error - attempt to add with overflow.
[Terminal] Type:


cargo build [Enter]

If we try to compile using cargo build, it compiles successfully.
[Terminal] Highlight:


attempt to add with overflow

But when we run the project we get an error as the addition takes place in runtime.
[Only narration] This reminds us that the integer variable is 32-bit.


So the maximum value it can take is 2147483647 which a 32-bit integer can store.


So if we add more to it, it is an overflow.


In order to overcome this error, we need to typecast the variable to a 64-bit integer while initializing.

Switch to Editor Switch back to the editor.
[Editor] Type:


let mut a:i64 = 1;

Update the variable declaration as shown.
[Editor] Highlight:


let mut a:i64 = 1;

Here we are telling the compiler that the initialized variable is of 64-Bit.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run
[Terminal] Highlight:


The value of a is 2147483648

We can see the output.


The initialized value is incremented by 1 and is successfully displayed in the terminal.

Slide: Float
  • Rust has 2 primitive types for Float similar to integers
  • f32 and f64
Slide: Float [show]

let a = 1.0;

  • Here the numbers are with decimal points.
  • For float, by default Rust allocates 64-bits
  • Here for let a = 1.0 Rust allocates 64-bits of memory.
Slide: Float [show]

let a:f32 = 1.0;

  • If you want Rust to allocate 32-bits of memory, we need to explicitly typecast to 32-bits using f32.
Slide: Boolean
  • As in most programming languages, in Rust also we have two possible values for boolean
  • True and False
Slide: Boolean

[show]

let a:bool = true;

  • To typecast a boolean variable we use bool
  • Typically these variables would be used whenever we set flags.
  • Depending upon the state of flag we allow further execution of the program.
Slide: Character


let a:char = ‘z’;

  • So far we have worked only with numbers.
  • Rust also supports letters.
  • The Character type is the most primitive alphabetic type.
  • The value should be declared between single quotes
  • Here’s an example of how a character can be declared.
Next, let’s learn about Compound Types.
Slide: Compound Data Types
  • Compound Types group multiple values of other types into one type.
  • Rust has two primitive Compound types namely, Tuples and Arrays.
Side: Tuples
  • A Tuple is a general way of grouping together some number of other values.
  • A Tuple can contain a variety of types.
  • We create Tuples by writing a comma separated list of values within parentheses.
Side: Tuples
  • Destructing is a process where a Tuple is broken into a number of parts using pattern matching.
  • Also we can directly access a Tuple element using a period.

Now let’s work on an example and understand this better.

[Terminal] Type:


cd .. [Enter]

Using cd command go to the Rust practice folder.
[Terminal] Type:


cargo new tuples [Enter]

Let us create a new project named tuples.


Type the command as shown.

Open Visual Studio Code editor. Switch to the editor.
Help -> Welcome Go to the Help menu and select Welcome.


We are back to the Welcome page

[Editor]


Welcome Page ->

Open Folder -> tuples

Open the created project by clicking on the Open folder link in the Welcome page.


Browse and locate the folder “tuples”.


Then click on the OK button at the top right corner.

[Editor] Click on tuples Under the EXPLORER section, expand the project folder “tuples” by clicking on it.
[Editor] Expand src and click on main.rs Then expand src and open the main.rs file.
[Editor] Type:


fn main() {

let tup:(i32,i32,i32) = (1,2,3);

let (x,y,z) = tup;

println!(‘x - {} , Y - {} , Z - {}‘, x,y,z);

}

In the editor, replace the code as shown.
[Editor] Highlight:


let tup:(i32,i32,i32) = (1,2,3);

Here, we first declare a tuple with three 32-bit integer values 1,2,3 respectively.
[Editor] Highlight:


let (x,y,z) = tup;

Then we declare 3 meaningful variables - x, y and z and then assign the variables to the already created tuple.
[Editor] Highlight:


println!(‘x - {} , Y - {} , Z - {}‘, x,y,z);

Using the print method we will print the respective values.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:

cd tuples [Enter]

Go to the project folder tuples using the cd command.
[Terminal] Type:


cargo run [Enter]

Now type cargo run
[Terminal] Highlight:


x - 1 , Y - 2 , Z - 3

We can see the output as x=1, y=2 and z=3.


Now let us understand what exactly is happening here.

Switch to Editor Switch back to the editor.
[Editor] Highlight:


let tup:(i32,i32,i32) = (1,2,3);

tup is a variable which has three values 1, 2 and 3.
[Editor] Highlight:


let (x,y,z) = tup;

We need to give these 3 values meaningful variable names.


So we have declared x, y and z and have assigned the tuple.


We call this as Destructing a tuple.

[Editor] Type:


let a = tup.0;

println!(“A = {}”,a);

Type this code inside the main function below the last line as shown.
[Editor] Highlight:


let a = tup.0;

tup.0 - this is how we directly access a tuple using period.


The index of the tuple starts from zero.

Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run
[Terminal] Highlight:


x - 1 , Y - 2 , Z - 3 A = 1

We see the output of A, x, y and z.
Slide: Arrays


Another way of storing multiple values is using an array.
  • Unlike a tuple, every element in an array should have the same data type.
  • Arrays in Rust are different as compared to other programming languages
  • As they have a fixed length.
Slide: Arrays
  • Once declared they cannot grow or shrink in size.
  • In Arrays, the data is allocated in a stack rather than a heap and has a fixed number of elements.

Let us take an example and understand this better.

Switch to Editor Switch back to the editor.
[Editor] Type:


let numbers = [1,2,3,4,5];

println!(“First Value = {}”, numbers[0]);

In the editor, type this code inside the main function below the last line as shown.


[Editor] Highlight:


let numbers = [1,2,3,4,5];

Here, we have declared a variable with the name numbers.


Then assigned an array with values of integer data type.

[Editor] Highlight:


println!(“First Element = {}”, numbers[0]);

Here, we are printing the first value by accessing the array starting with index 0.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run
[Terminal] Highlight:


First Value = 1

We see the output as the first value in the array is displayed.
Switch to Editor Switch back to the editor.
[Editor] Type:


println!(“12th Element = {}”, numbers[11]);

Now type this code, inside the main function below the last line

as shown.

[Editor] Highlight:


println!(“12th Element = {}”, numbers[11]);

We now have 5 values in the array.


Let us try to access the nth element greater than 5, say, 12th element where there is no value.


Let’s see what will happen.

Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run.
[Terminal] Highlight:


index out of bounds, the length is 5 but the index is 11.

We see an error- index out of bounds, the length is 5 but the index is 11.


So, arrays in Rust are different as compared to other programming languages


That’s because they have a fixed length.

Only narration With this we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • Supported Data Types
  • Scalar Data Types
  • Compound Data Types and
  • Its types in Rust.
Slide: Assignment As an assignment,
  • Go to the project folder rust-assignment
  • In the main.rs file
    • Initialize a variable named m and assign an array to it
    • The array should contain 5 numbers as elements
    • Print the elements of the array
  • Compile and execute the project
  • Observe the output in the Terminal
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
Slide: Forum questions Pls post your timed queries in this forum
Slide: Acknowledgement Spoken Tutorial Project is funded by Ministry of Education, Government of India
Slide: Thanks This is Jayesh signing off. Thank you for joining

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389