Category Archives: Rust Tutorial

Rust Tutorial

Rust If in Let Statement

Rust If Let Statement

Rust If Let Statement is a combination of if and let statements in a more concise way, where value of if statement is assigned to let statement.

Syntax:-

Here, if Condition is a Boolean expression that results in either True or False, if it results in True then statements inside if body are executed and result value is assigned to var_name, if it results in False then statements inside else body are executed and result value is assigned to var_name.

Example :-

Output :-

rust_if_in_let_statement

Rust if else if Statement

Rust if else if Statement

In Rust, if..else..if statement allows us add alternative set of test conditions in if..else statement using else-if and single else statements for if condition. In such way if..else..if statement is used to select one among several blocks of code to be executed.

Rust if..else..if Statement Flow Diagram

rust-if-else-if

rust-if-else-if

Syntax:-

Example:-

Output:-

rust_if_else_if_statement

Rust Nested If else statement

Rust Nested If else statement

In Rust, when there is an if statement inside another if statement then it is known as nested if else. Nested if else can also be simplified using Swift Switch Statement.

Syntax:-

Example:-

When we run the above rust program, will see following output –

Output:-

rust_nested_if_statement

Rust if else Statement

Rust if else Statement

In Rust, when we want to execute a block of code when if condition is true and another block of code when if condition is false, In such a case we use if…else statement.

Rust If…else Statement Flow Diagram

rust-if-else-flowchart

Syntax:-

Here, Condition is a Boolean expression that results in either True or False, if it results in True then statements inside if body are executed, if it results in False then statements inside else body are executed.

Example:-

Output:-

rust_if_else_statement

 

Rust if Statement

Rust if Statement

If statement allows a block of code to be executed only when a specified condition is true. An if statement evaluates a boolean expression followed by one or more statements. The given boolean expression results in a boolean value that can only be either true or false.

Rust If Statement Flow Diagram

swift-if-statement

swift-if-statement

Syntax:-

Here, Condition is a Boolean expression that results in either True or False, if it results in True then statements inside if body are executed, if it results in False then execution is skipped from if body.

Example:-

Output:-

rust_if_statement

 

Rust Decision Making Statements

Rust Decision Making Statements

There are case where we want a a block of code to be executed when some condition is satisfied. In Rust, we have rich set of Decision Making Statement that enable computer to decide which block of code to be execute based on some conditional choices. Decision making statement statements is also referred to as selection statements.

Decision making statement evaluates single or multiple test expressions which results is “TRUE” or “FALSE”. The outcome of the test expression/condition helps to determine which block of statement(s) to executed if the condition is “TRUE” or “FALSE” otherwise.

In Rust, we have following decision making statements –

Rust Decision Making Statements
Statement Description
Rust if Statements Block of statement executed only when specified test expression is true.
Rust if else When we want to execute some block of code if a condition is true and another block of code if a condition is false, In such a case we use if….else statement.
Rust if else if When we want to add multiple condition checks in single if else statement then by using swift if else-if else statement we can easily add multiple conditions.In if else-if else statement we have a option to add alternative else if statements but we are limited to have only one if and else block in statement.
Rust Nested If When there is an if statement inside another if statement then it is known as nested if else.

Rust Type Casting

Rust Type Casting

Type Casting is a mechanism which enables a variable of one datatype to be converted to another datatype.When a variable is typecast into a different type, the compiler basically treats the variable as of the new data type.

Rust provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as keyword.

Type of casting

  • implicit or automatic
  • explicit or given

Implicit or automatic

In implicit or automatic casting compiler will automatically change one type of data into another. Rust provides no implicit type conversion (coercion) between primitive types. Coercion between types is implicit and has no specified syntax. Coercion is usually be seen in let, const, and static statements; in function call arguments; in field values in struct initialization; and in a function result.

Example:-

The coercion can be used in removing mutability from a reference as following –

Mutability of a raw pointer can removed as following –

A references can be coerced to raw pointers as follows –

Explicit or given

In Rust, a variable can be explicitly type cast using the as keyword. The as keyword does safe casting. Typecasting should always be used in right order (low to higher datatype). Type casting in wrong places may result in loss of precision, which the compiler can signal with a warning.

Example:-

In Rust, type casting rules are same as of C Programming .

Rust Constants

Rust Constants

Constants are basically immutable literals whose values cannot be modified or changed during the execution of program. In Rust, constants live for the entire lifetime of a program and constants in Rust have no fixed address in memory.

Initializing Constants In Rust

The Constants are created in the same way you create variables but instead of using the let keyword here we use the const keyword and by convention constant names are always preferred in uppercase.

Syntax:-

or

Example:-

 

Rust Variables

What is Variables?

Variables is an identifier used to refer memory location in computer memory that holds a value for that variable, this value can be changed during the execution of the program. When you create a variable in Rust, this means you are allocating some space in the memory for that variable. The size of memory block allocated and type of the value it holds is completely dependent upon the type of variable.

Declaring Variables In Rust

In Rust, we can declare variable bindings first, and initialize them later. In Rust, variables are declared using the let keyword followed by variable name that you want to declare, optionally a colon (:) and then the data type you want to hold in that variable.

Syntax:-

or

Initializing Variables In Rust

In Rust, a variable bindings must be initialized with a value before they are used. The assignment operator (=) is used to assign values to a variable, the operand in the left side of the assignment operator (=) indicates the name of the variable and the operand in the right side of the assignment operator (=) indicates the value to be stored in that variable.

Syntax:-

or

or

or

Example:-

Output:-

rust_variable_initialization

Type Annotations

Rust is a type inferred language, which allows us to drop the type annotation from the declaration. In Rust, compiler automatically infer(know) the type of data we want to store based on the initial value we assign. In Rust, this feature is termed as ‘type inference’.

Example:-

Here, type annotation is not used in the declaration but the Rust compiler simply infer the type automatically for us.

Rust Mutability

In Rust, by default variables are immutable. Once a variable is assigned an initial value, you will not allowed to change that value.

Example:-

This will result in error –

However, if you still have the option to make your variables mutable by adding the mut keyword in front of variable name.

Example:-

Printing Variables or String Interpolation

In Rust, println!() function is used to print the current value of a variable. String interpolation can be done by including two curly braces ({}) in your string to print, Rust compiler will interpret this as a request to interpolate with some value. Next, the comma is used to separate arguments we are interpolating with.

Example:-

Output:-

rust_print_variable_value_string_interpolation

Rust Custom Types

Rust Custom Types

Custom type are data types usually derived using existing data type with another identifier.This user defined data type identifier can later be used to declare variables. In short its purpose is to redefine the name of an existing data type. Rust provides following custom types –

Rust struct

In Rust, we can use arrays when we want hold multiple element of the homogeneous data type in single variable, but what if we want to hold heterogeneous data type element, using structure you can wrap one or more variables that may be in different data types into one.

Rust enum

An enumeration is a set of predefined named values, called as members. Enumerations are useful when we want deal with limited set of values for variable. For example you can think of the colors of a traffic light can only be one of three colors– red, yellow or green.

 

Rust Primitives

Rust Primitives

A primitive type is a data type is a basic building block provided by any programming language. The primitive data type are predefined by the language and for which the programming language provides built-in support. The Rust provides a range of primitive data types –

Numbers :- The Number data type is used to hold the numeric values. Rust supports following numerical data types –

Integer:- Integers are used to store whole numbers. Rust supports several integer types, varying internal sizes for storing signed and unsigned integers.

Rust Signed Integers
Type Size Description Range
i8 8 bits 8 bit Signed Integer (two’s complement) -128 to 127
i16 16 bits 16 bit Signed Integer (two’s complement) -215 to 215 -1
i32 32 bits 32 bit Signed Integer (two’s complement) -231 to 231 -1
i64 64 bits 64 bit Signed Integer (two’s complement). They can also be represented in octal and hexadecimal -263 to 263 -1
Rust Unsigned Integers
Type Size Description Range
u8 8 bits 8 bit Unsigned Integer 0 to 127
u16 16 bits 16 bit Unsigned Integer 0 to 216 -1
u32 32 bits 32 bit Unsigned Integer 0 to 232 -1
u64 64 bits 64 bit Unsigned Integer 0 to 264 -1

Rust Float:- A Float type is used to store numbers that contain a decimal component (real numbers). Rust provides two floating point types: f32 and f64. The f32 and f64 are used to represent single and double precision numbers.

Rust variable Size Numeric Types :-

Rust Variable Size Numeric Types
Type Signed/Unsigned Description
isize Signed It’s size depends on the size of a pointer of the underlying machine.
usize Unsigned It’s size depends on the size of a pointer of the underlying machine.

Boolean :- The Boolean data type is used to represent the truth values, which can be either True or False. Boolean are commonly used in decision making statements.

Example:-

Output:-

Characters (char) :- The character data type is used to hold the single literal (single Unicode scalar value). Character are declared using single quotes. It can also include emoji or languages character other than English using. Unlike other programming languages Rust’s char is of four byte instead of a single byte.

Example:-

Output:-

String (str) :- A string is a series or sequence of Unicode scalar values encoded as a stream of UTF-8 bytes. In Rust, string handling is bit different from other programming languages. In Rust, we have two types of strings: &str and String. The &str is termed as “string slices”. String slices are basically a reference to a sequence of UTF-8 bytes. A string slice is always of fixed size, and cannot be changed. While, a String series or sequence of characters of – letters, numbers, and special characters. Strings can created by converting from a string slice using the to_string method.

Array :- The array is collection of homogeneous elements placed in contiguous memory locations that can be accessed individually by adding an index or subscript to a unique identifier. By default, arrays are immutable.

Example:-

Output:-

Slice :- A slice is a reference to another data structure. They are useful for same and efficient access to memory location. The slices can be mutable or immutable, and have a defined length.

Tuple :- Tuple is an ordered sequence of comma-separated values (items or elements). Once a tuple is created their elements and size can not be changed.A Tuple is defined within parentheses () where items are separated by commas.

Example:-

Rust Data Types

Rust Data Types

Variables are used to represent reserved memory locations that is used to store values, when we create a variable we are a suppose to allocate some memory space for that variable. Rust is a statically typed programming language. This means that variables always have a specific type. Every variable have data type associated to it, data type for a variable defines –

  • The amount of memory space allocated for variables.
  • A data type specifies the possible values for variables.
  • The operations that can be performed on variables.

In Rust, data types are categorized into following two category –

  • Primitive Types (Built-In)
  • Custom Types

Rust has following primitive data types –

  • Numbers
  • Boolean
  • Characters
  • String
  • Array
  • Slice
  • Tuple

Rust has following custom data types –

  • Structure
  • Enumeration