Rust Tutorial

Are you seeking a quick guide to learn Rust? You can stop your search here. You can find everything you need about Rust in this Rust tutorial. This tutorial will take you through the core Rust concepts, setting up the Rust environment, and many more. By the end of this Rust tutorial, you will get familiar with Rust programming concepts along with the competence to write and run Rust programs effortlessly.

Rust is a fast, highly reliable, and memory-efficient programming language. It is emerging as one of the desired languages for software developers in recent years. According to a recent survey of Statista, Rust is ranked next to the popular programming languages such as PHP, Go, and PowerShell.

It is a great idea to learn the Rust language as soon as possible if you want to grasp the job opportunities that will surge in the near future. In this Rust tutorial, you will go from basics to advanced Rust concepts step by step. You will mainly learn to install Rust software on your Windows machine and practice Rust programs for a better hands-on experience.

Table of Contents:

What is Rust?

Rust is essentially a low-level programming language that was released in May 2015. It is a young language that helps developers to write highly safe, reliable, and efficient software programs. As Rust is a general-purpose language, you can develop multiple software applications, including embedded systems, gaming, bare-metal development, etc.

Rust has a user-friendly compiler that removes the common bugs usually found in other languages. It demands robust testing methods, time, and effort to remove these bugs. That's why Rust has become the buzzword among developers who leverage Rust to accelerate software development and boost productivity.

Okay! Rust comes into the limelight nowadays, even though many popular programming languages still dominate the software development world.

Why Rust?

Check out the reasons below to understand why Rust is gaining importance among developers.

  • Rust provides better memory performance without using the garbage collector
  • It is a fast-growing programming language along with an evolving ecosystem
  • It comes with a logical and functional syntax, which simplifies Rust programming
  • It completely eliminates bugs at compile time and speeds up software development
  • It facilitates an asynchronous processing model to create and run individual functions and then integrate them together.
  • It offers well-versed documentation to support the developer community
  • It offers a multi-editor with auto-formatter and type inspections 
  • It provides an integrated package manager
  • It offers improved scalability and concurrency.

Well! Hope you have understood why Rust is becoming popular nowadays. Next, we will look at the features of Rust in the following section.

This topic is essential for the Rust interview, and our trainer has offered extensive coverage of it within our Rust Training program.

Features of Rust:

Rust comes with noteworthy and impressive features, undeniably. Let's explore them now.

  • Memory Management 

Rust provides exceptional memory safety. Its ownership and borrowing system only allows a single ownership of any data. It helps to prevent data races and memory leaks. Rust's strong typing system strictly allows for handling data as intended. It helps to prevent buffer overflows. 

  • Better Concurrency 

Rust's robust type system will enable developers to write concurrent codes without creating data races.

  • Zero-cost Abstractions

Rust abstractions don't generate any runtime overhead. In other words, Rust supports high-level abstractions without creating any runtime performance costs. 

  • Compiled Language

In its most basic form, Rust is a compiled language. It means the Rust codes can be converted into machine codes before the execution. 

  • C – Bindings

Rust can interoperate with the C language seamlessly. It is done with the help of the foreign function interface to make communication with 'C' APIs.

  • Web Assembly Support

Rust is good in web assembly module development. This is because Rust offers excellent low-level control and memory safety.

Installing Rust on Windows:

This section will guide you in installing Rust on your Windows machine. The development environment that you create will help to play around with Rust programs.

Let's go through the step-by-step procedure below:

Step -1: Installing Visual Studio Code on Windows

  • Step -1: Installing Visual Studio Code on Windows  https://code.visualstudio.com/download
  • Next, click on the Windows option for downloading.
  • A popup will come up where accept the agreement and then click the Next button.
  • Install the software and then click the finish button.
  • Finally, you will get the screen as shown below.

Step – 2: Installing the Visual C++ build tools on Windows

Step 3: Installing Rust on Windows

  • Click the link below to download the latest stable version of Rust – Rust 1.76.0.  https://Rustup.rs/
  • A Windows command prompt will open up where enter '1' for installation
  • Once the installation is over, you will be asked to press the enter button on your keyboard. 
  • Hit the enter button and complete the installation.

Step 4: Verifying the Rust installation

  • Now, open the PowerShell command prompt on your machine 
  • Enter the below command in the prompt  rustc  --version
  • Now, the below output will come in the prompt screen, showing the latest version of the Rust software.
    PS C: \WINDOWS\System32> rustc -- version
    rustc 1.76.0 (07dca489a 2024-02-04)
  • Then, enter the below command to ensure the cargo version  cargo --version
  • After that, you will get the below output in the prompt screen, displaying the latest cargo version.

Cheers! You have successfully installed the Rust software on your Windows machine. Next, we will start working on the Rust language with a simple Hello World example.

MindMajix Youtube Channel

Example - Hello World:

This Rust tutorial consists of two stages. In the first stage, you will create a new directory to store your Rust codes. You will run the 'Hello World' program in the second step.

Creating a New Directory

  1. First, open the Windows PowerShell command prompt.
  2. Right-click on the Windows PowerShell prompt on your Windows machine taskbar.
  3. Now click the Windows PowerShell ISE – a text editor for Rust programs.
  4. Copy the below code in the Windows PowerShell ISE command prompt.
    mkdir ~/projects
    cd ~/projects
    mkdir hello_world
    cd hello_world
  5. Your project directory will open as shown in the below image.
  6. After that, create a new source file using your notepad with the .rs extension. Open the file and copy the code below.
    fn main() {
    println!("Hello, world!");
    }
  7. Save the file in the hello_world folder in the directory you created earlier.
  8. Then, copy the below code in the PowerShell Window in the ~/projects/hello_world directory.
  9. Run the file, and you will get the output below. 
    PS C:\Users\user\projects\hello_world> rustc main.rs. \main.exe
    
    Hello, world!

Congrats! You have successfully run your first Rust program with the help of this Rust tutorial.     

Next, we will dive into learning the core concepts of rust programming. It will help to elevate your rust programming skills to new heights.

Rust – Primitives: 

Know that the Rust language comes in many types. They are known as primitive types. The types are usually built into the Rust language. Apart from the built-in types, the Rust standard library offers many other useful types to facilitate developers.

Let's take a look at them now.

  • Booleans

Rust has a built-in data Boolean type with two values – True and False. This Boolean type is also known as bool. The if conditions in the Rust widely use the Boolean types.

#! [allow(unused_variables) ]
fn main() {
let x = true;
let y: bool = false;
}
  • Numeric Types

Rust has different categories of numeric types: fixed and variables, signed and unsigned, and integer and floating-point. Every numeric type consists of two parts. One is the category of the number. Another part is the number size. Consider the example numbers in the below image.

let x = 32; // 'x' has type i32'.

let y = 2.0; // 'y has type f64'.

In the first example, 32 is an integer number with a 32-bit size. In the second one, the number is 2.0, a floating number with a 64-bit size. Know that u8, u16, u32, u64, i8, i16, i32, i64, f32, and f64 are the different numeric types used in Rust language.

  1. Signed and unsigned number types
    In Rust, we use two integer numeric types such as signed and unsigned. A signed four-bit number can store values from -8 to +7. On the other side, an unsigned four-bit number can store values only from 0 to +15. Signed numbers generally follow the two's complement representation.
    Signed numbers are usually denoted by the 'i' category. For example, consider the number type i8, which is an eight-bit signed number. On the other side, unsigned numbers are denoted by the 'u' category. For example, consider the number type u8, which is an eight-bit unsigned number.
  2. Fixed-size types
    Fixed-size numeric types have a specific number of bits, such as 8,16,32,64, to represent values. Let's take u16, an unsigned 16-bit integer, to understand it better. On the other hand, consider i64, which is a signed 64-bit integer.
  3. Variable-size types
    Variable size is another numeric type of rust language used based on the machine architecture. The category of this type is 'size'. There are two types of variable sizes, such as signed and unsigned. They are denoted as 'isize' and 'usize' respectively.
  4. Floating point types
    Rust comes with two floating point numeric types such as f32 and f64.
  • Arrays

Rust supports list types. It helps to represent a sequence of strings or numbers. An array has the same type of fixed size of elements. Note that arrays are immutable. The below image shows an example of arrays.

fn main() {
let a = [1, 2, 3]; // a: [i32; 3]
let mut m = [1, 2, 3]; // m: [i32; 3]
}
  • Slices:

You can use slices to use a portion of an array in a safe way without copying. Slices typically have a defined length. They can be mutable or immutable.

  1. Slicing syntax

    Rust allows you to use the [] and & to create a slice from an array. Here, the [] symbol helps to define the slice length.
  • Tuples

A tuple is typically an ordered list of fixed size, as shown below.

#! [allow(unused_variables)]
fn main() {
let x = (1, "MindMajix");
}

This code can be annotated as follows:

#! [allow(unused_variables) ]
fn main() {
let x: (i32, &str) = (1, "MindMajix");
}

If two tuples have the same type, you can assign one tuple to another, as shown in the code below.

#! [allow(unused_variables) ]
fn main() {
let mut x=(1,2); // x: (i32, i32)
let y= (2, 3); // y: (i32, i32)
x = y;
}

You will get the output below When you run the code.

1 #! [allow(unused_variables) ]
2 - fn main() {
3 let tuple = (1, 2, 3);
4 let x = tuple.0;
5 let y = tuple.1;
6 let z = tuple.2;
7 println!("z is {}", z);
8 }

Rust – Custom Types:

In Rust programming, custom types are created using the keywords Enum and Struct. Enum stands for an enumeration, whereas Struct stands for a structure.

Let's have a look at them one by one.

  • Structures

The struct keyword creates three types of structures: Classic-C Structs, Tuple Structs, and Unit Structs.

  1. Classic-C structs
  2. Tuple Struts, or Tuples
  3. Unit structs

The below Rust code shows the use of unit struct with the output.

#[derive(Debug) ]
struct Person {
name: String,
age: u8,
}
fn main() {
let name = String :: from("MM");
let age = 10;
let MM = Person { name, age };
println!("{ :? }", MM);
}

Output

warning: 2 warnings emitted
Person { name: "MindMajix", age: 10 }
  • Enums:

You can use enums to create a variant type. Note that a variant that is valid as struct is also known as an enum.

The below code shows the use of enums in creating a web event.

enum WebEvent {
PageLoad,
PageUnload,
}
fn inspect(event: WebEvent) {
match event {
WebEvent: : PageLoad => println! ("page loaded"),
WebEvent: : PageUnload => println! ("page unloaded"),
}
}
fn main() {
let load  = WebEvent : : PageLoad; 
let unload = WebEvent: : PageUnload;
inspect(load);
inspect(unload);
}

Output:

/tmp/YL6sdfjzwn/main
page loaded
page unloaded
  • Constants

Rust comes with two types of constants. You can declare the constants in any scope. Even it can be a global scope. Both the constants require explicit type annotation.

Const – It is an unchangeable value

Static – It is a mutable variable, but it comes with a static lifetime. Modifying a mutable variable is not considered a safe action.

To understand it better, consider the below Rust code that uses constants in if statements.

static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;
fn is_big(n: i32) -> bool {
n > THRESHOLD
}
fn main() {
let n = 5;
println!("This is {}", LANGUAGE);
println!("The threshold is {}", THRESHOLD);
println!("{} is {}", n, if is_big(n) { "big" } else { "small"});
}

Output:

/tmp/YL6sdfjzwn/main
This is Rust
The threshold is 10
5 is small

Rust – Changing Types

Rust offers developers effective mechanisms to modify user-defined and primitive types. Not only that, it provides methods to define the types.

The modification of types can be done in four ways. Let's address them one by one in the following.

  • Casting between Primitive Types

Rust doesn't support implicit type conversion between primitive types. But at the same time, it allows explicit type conversion by using the ‘as’ keyword. The following will show you the results of using the explicit and implicit types conversion.

The below code will show you the use of implicit type conversion. It will create an error during execution. 

#! [allow(overflowing_literals)]
fn main() {
let decimal = 65.4321_f32;
// Error! No implicit conversion
let integer: u8 = decimal;

The below example shows the use of explicit type conversion with the as keyword.

#! [allow(overflowing_literals)]
fn main() {
let decimal = 65.4321_f32;
// Explicit conversion
let integer = decimal as u8;
let character = integer as char;
  • Using Type Inference

In this method, Rust's smart inference engine plays a key role in identifying how variables are used to infer their types. The below code explains the same.

fn main() {
let elem = 7u8;
let mut vec = Vec :: new();
vec.push(elem);
println!("{ :? }", vec);
}

Output:

[7]
  • Suffixing the Type of Literals

In this method, the type of a numeric literal is suffixed with the literal. For example, consider the numeric literal 45i32. Here, the type integer 32 is suffixed with the literal 45. The Rust compiler considers i32 for integers. Similarly, it takes i64 for floating-point numbers.

The code below will explain the use of suffixing types with literals.

fn main() {
// Suffixed literals
let x = 1u8;
let y = 2u32;
let z = 3f32;
println!("size of 'x' in bytes: {}", std: :mem: :size_of_val(&x));
println!("size of 'y' in bytes: {}", std :: mem: : size_of_val(&y));
println!("size of 'z' in bytes: {}", std: :mem: : size_of_val(&z));
}

Output:

/tmp/2b7MPfLOh0/main
size of 'x' in bytes: 1
size of 'y' in bytes: 4
size of 'z' in bytes: 4
  • Aliasing types:

You can use the type statement to assign a new name to the existing type. But the rule is that the new names must be in the ‘UpperCamelCase’ format. Note that this rule does not apply to primitive types.

The below code will show you the use of aliasing in Rust.

type NanoSecond = u64;
type Inch = u64;
type U64 = u64;
fn main() {
let nanoseconds: NanoSecond = 5 as U64;
let inches: Inch = 2 as U64;
println!("{} nanoseconds + {} inches = {} unit?",
nanoseconds,
inches,
nanoseconds + inches);
}

Output:

/tmp/2b7MPfL0h0/main
5 nanoseconds + 2 inches = 7 unit?

Rust – Flow of Control:

This section deals with modifying the control flow through various methods.

  • If-else

Although if-else statements used in Rust are similar to other languages, no parentheses are used in Boolean expressions in the Rust language. Also, every condition in the if-else statement contains a block. Note that all branches must return the same type in this conditional statement.

fn main() {
let mut count = 0u32;
println!("Let's count until infinity!");
loop {
count += 1;
if count == 4 {
println!("four");
continue;
}
println!("{}", count);
if count == 6 {
println!("OK, that's enough");
break;
}
}
}

Output:

PS C:\Users\user\projects\tutorial> rustc main.rs. /main
Let's count until infinity!
1
2
3
four
5
6
OK, that's enough
  • Loop

Rust uses the Loop keyword to facilitate loops in programs. You can employ the break statement if you need to break a loop. Similarly, you can use the continue statement if you want to skip from the remaining iteration and start a new iteration.

fn main() {
let mut n = 1;
while n < 16 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
n += 1;
}

Output:

PS C:\Users\user\projects\tutorial> rustc main.rs. /main

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
  • For and Range

Rust offers an easy way to iterate using the notation a…b. This includes the 'a' value and excludes the 'b' value. 

fn main() {
// 'n' will take the values: 1, 2, ... , 100 in each iteration
for n in 1 .. 15 {
if n % 7 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}

Output:

PS C:\Users\user\projects\tutorial> rustc main.rs. /main

1
2
fizz
4
buzz
fizz
fizzbuzz
8
fizz
buzz
11
fizz
13
fizzbuzz
  • Match

Rust offers the match keyword for pattern matching. The example below will show the use of pattern matching and match keyword.

fn main() {
let number = 15;
println!("Tell me about {}", number);
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println! ("This is a prime"),
13 ..= 19 => println!("A teen"),
=> println!("Ain't special"),
}
}

Output:

PS C: \Users\user\projects\tutorial> rustc main.rs. /main

Tell me about 15
A teen

Rust - Modules:

Rust offers a robust module system that you can use to split Rust codes into logical units. A module is a collection of functions, structs, blocks, and more.

Let's discuss the various features of the Rust modules in the following.

  • Visibility

In the Rust language, items in a module have private visibility by default. However, you can override the private visibility using the pub modifier. Besides, you can access only the public items of a module.

The below codes show the use of a public modifier in accessing the public items of a module.

mod my_mod {
fn private_function() {
println!("called my_mod :: private_function()'");
}
pub fn function() {
println!("called my_mod :: function()'");
}
pub fn indirect_access() {
print!("called 'my_mod :: indirect_access()', that\n> ");
private_function();
}
  • Struct Visibility

Structs come with an extra level of visibility. You can override the visibility using the pub modifier. The code below will explain the role of structural visibility to you.

  • Use Declaration:

You can use the use declaration if you want to bind a full path to a new name. It will make access easy. The below code will show you the application of use declaration.

Great! You have completed learning the Rust tutorial. The Rust concepts and examples must have helped you level up your knowledge of the Rust language.

Key Takeaways:

  • Rust is one of the emerging programming languages that offer memory efficiency and high reliability 
  • It is the language that offers concurrency, high speed, and safety
  • It provides an asynchronous processing model, which allows developers to run independent functions
  • It supports developing gaming applications, IoT applications, powerful browsers, etc.
  • It supports zero-cost abstraction so developers can hide internal details of codes effectively
  • It offers user-friendly syntax so developers can develop codes with speed.

Frequently Asked Questions

1. What is the latest version of Rust?

The latest stable version of Rust is 1.76.0. It is a reliable, high-performance, and highly productive release of Rust.

2. Is learning Rust easy?

Yes, learning Rust is as easy as walking in a park. You must have a passion for learning and be eager to become the best coder. That's all! In MindMajix, our expert trainers deliver Rust training in a simplistic way so any learner can become a master in Rust quickly.

3. Is learning Rust worth it?

Rust is a fast-growing coding language. Rust developers can make an average salary of over 6 LPA in India. They can get an average salary of over 110k USD annually in the USA. From these statistics, you can understand that kick-starting a career in Rust is promising and worthy.

4. Is there any prerequisite to learning Rust?

No. If you have a basic knowledge of computer operating systems, data types, and memory management, it will be helpful to learn Rust effortlessly.

5. Is Rust faster than Java?

Rust is faster than Java. This is because Rust consumes less memory than Java. Also, it quickly eliminates the common bugs of Java. As Java relies on the garbage collector for memory management, Rust overtakes Java.

6. Is Rust better than C++?

C++ is one of the high-performing OOP languages with a vast user community. On the other hand, Rust is the emerging programming language that offers high speed, safety, reliability, and excellent memory management. So, neither C++ nor Rust is better than the other. The right tool selection depends on the developer's comfort and the application requirements.

Conclusion:

On a final note, we hope that you have enjoyed and learned a lot from this Rust tutorial. This tutorial might have helped you learn Rust, from the basics to advanced concepts. This blog has covered the primitives, modules, custom types, and more in-depth. The step-by-step procedure to install Rust on your machine and the simple 'Hello World' program should have helped you to gain solid practical skills.

If you want to explore Rust further, you can sign up for the Rust training with MindMajix. It will help you gain comprehensive Rust knowledge and sound hands-on skills. Undeniably, the certification will move up the career ladder to greater heights. 

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Rust TrainingNov 19 to Dec 04View Details
Rust TrainingNov 23 to Dec 08View Details
Rust TrainingNov 26 to Dec 11View Details
Rust TrainingNov 30 to Dec 15View Details
Last updated: 06 Mar 2024
About Author

Kalla Saikumar is a technology expert and is currently working as a Marketing Analyst at MindMajix. Write articles on multiple platforms such as Tableau, PowerBi, Business Analysis, SQL Server, MySQL, Oracle, and other courses. And you can join him on LinkedIn and Twitter.

read less