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:
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.
Check out the reasons below to understand why Rust is gaining importance among developers.
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. |
Rust comes with noteworthy and impressive features, undeniably. Let's explore them now.
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.
Rust's robust type system will enable developers to write concurrent codes without creating data races.
Rust abstractions don't generate any runtime overhead. In other words, Rust supports high-level abstractions without creating any runtime performance costs.
In its most basic form, Rust is a compiled language. It means the Rust codes can be converted into machine codes before the execution.
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.
Rust is good in web assembly module development. This is because Rust offers excellent low-level control and memory safety.
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 – 2: Installing the Visual C++ build tools on Windows
Step 3: Installing Rust on Windows
Step 4: Verifying the Rust installation
rustc --version
PS C: \WINDOWS\System32> rustc -- version
rustc 1.76.0 (07dca489a 2024-02-04)
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.
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
mkdir ~/projects
cd ~/projects
mkdir hello_world
cd hello_world
fn main() {
println!("Hello, world!");
}
~/projects/hello_world
directory.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.
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.
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;
}
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.
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]
}
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.
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 }
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.
The struct keyword creates three types of structures: Classic-C Structs, Tuple Structs, and 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 }
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
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 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.
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;
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]
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
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?
This section deals with modifying the control flow through various methods.
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
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
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
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 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.
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();
}
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.
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.
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.
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.
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:
Name | Dates | |
---|---|---|
Rust Training | Dec 24 to Jan 08 | View Details |
Rust Training | Dec 28 to Jan 12 | View Details |
Rust Training | Dec 31 to Jan 15 | View Details |
Rust Training | Jan 04 to Jan 19 | View Details |