Introduction to Rust

Introduction

To learn a new programming language, we need to learn its introduction, why it is getting used, and its basics. So, let's have a look at the introduction to Rust.

Rust is a modern system programming language that aims to provide safe and efficient code. It was created by Graydon Hoare while he was working at Mozilla, and later on, it was acquired by Mozilla. It is designed to write code for low-language system programming with a high level of abstraction. The syntax of Rust is similar to that of C++. Rust has a lot of unique features like crates, traits, ownership, and borrowing. Overall, it is a great choice for building high-performance systems.

Rust has gained popularity in recent years, particularly in the areas of system programming, networking, and web development. Many tech giants, such as Microsoft, Amazon, and Dropbox, have started using Rust in their products and services. Let's have a look at some of the main features of Rust.

Features of Rust

  • Cargo, a built-in package manager and build system.
  • Pattern matching for concise and expressive control flow.
  • Concurrency primitives for building concurrent and parallel programs.
  • Traits and generics for abstracting over different types and behavior.

How to install Rust on our System?

The steps to install Rust varies according to the platform you are using, like Windows, Linux, or Mac OS.

For Windows

Step 1. Go to the official website of Rust

Rust

Download the rustup version according to your system configuration.

Step 2. Double-click the setup that you have downloaded and install it. A cmd window will open as below.

rust

Step 3. Here, you have three options to install Rust into your system. Enter 1 if you want to install it quickly. 

rust

The below window will open. Press Continue to install this.

rust

Now, your Visual Studio Installer will start downloading the necessary files. Let it complete the download.

rust

Now you have your Rust installed. You can confirm it by running the command to check the Rust version.

For Linux

To install Rust in a Linux system, copy and paste the below command into the terminal.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Once you run the above command, you will have Rust installed on your Linux system. You can confirm this by checking the version of Rust.

How to write your first program in Rust?

Writing our first program in any language is essential as it gives us confidence in learning that language. So, let's create our first project in Rust.

Step 1. To create a new project, write the cargo new project name in the command prompt. A file structure will be created for your project named project name.

rust

Rust will automatically create this project with the main.rs file, which contains the Hello World program by default.

fn main() {
   println!("Hello, world!");
}

In the above example, we have created a main method which is the entry point of every program using the fn keyword. In the next line, we print the Hello world using println!() macro.

Step 2. Go to the exact location of your project. Then type "cargo run". The cargo run will compile and run your project, and you will get the output.

rust

Here, we got our Hello World output. We have successfully written our first program and are good to go to the basics, like data types and variables.

Variables and Data Types in Rust

The variable is a container to store something in memory, be it an integer, floating point value, or string. Rust is a statically-typed language, meaning that every variable must have a type known at compile-time. In Rust, by default, variables are immutable; that is, value cannot be changed.

Example

fn main()
{
  let x=5;
  println!("x is :{}",x);
  x=10;
  println!("x is :{}",x);
}

Output

rust

In the above example, we created a main function in which we created a variable x and assigned 5. In the next line, we print the value of x. In the next line, we try to change the value of x by assigning it 10. In the next line, we print its value.

Once we execute this program, we get an error at line 5 as in Rust, variables are immutable, and we are trying to change the value of a mutable variable which is wrong. Hence, before changing the value of x, we will have to make it mutable by adding the mut keyword during the declaration of variable x.

Now talking about data type, Rust provides several built-in data types, including integers, floating-point numbers, booleans, characters, and strings.

Let's consider the following example to understand more about data types

fn main()
{
  let x:i64=5;
  let y:f32=3.45;
  let z:String=String::from("Rust");
}

In the above example, we created three variables: x, y, and z. x is made of i64 type, i.e., a signed integer of 64 bits, and we have assigned an integer value to it. y is made of f32 type, i.e. 32-bit floating point number, and z is made of String type, and we have assigned a string to it.

To know more about data types, refer to this article - What Are The Data Types In Rust?

Conditional Statements in Rust

Conditional statements are statements in which, if the condition is met, then only a set of statements will execute. This is highly useful in situations when we want a particular code to run only when it meets some condition that we have specified. We can use the if keyword to create conditional statements.

Let's consider an example in which we use the conditional statement if.

fn main()
{
  let x = 42;
  if x > 10 {
    println!("x is greater than10");
  }
  else{
    println!("x is less than or equal to 10");
  }
}

In the above example, we created a variable named x and assigned it some value. In the next line, we check if x is greater than 10. This code prints "x is greater than 10" because the value of `x` is greater than 10.

Loop in Rust

A loop is a control structure that allows a program to repeat a set of instructions multiple times. It is a way of automating repetitive tasks and making a program more efficient and concise.

In Rust, we have three types of loops. They are as follows,

  1. loop- It creates an infinite loop that can be exited only using the break keyword. It is used when we want to repeat a set of codes until a certain condition is met.
  2. for- It creates a loop that iterates over a range, an iterator, or a collection. It is useful when you want to iterate over a sequence of elements.
  3. while- It executes as long as a certain condition is true. It is useful when you want to repeat a block of code until a certain condition is no longer true.

To know more about loops, refer to this article - How to use loops In Rust?

Functions in Rust

Functions are a set of code written to perform a particular functionality. There are many cases where we have to use functionality or a set of code multiple times. Writing the same code again makes our program unnecessarily lengthy and takes time. Here, the functions come in the frame. They increase code readability and save our time too. Whenever we need the function, we can call the function instead of writing the whole code again.

Functions are a fundamental building block in Rust programs. We've already seen the main function, which is the entry point of the program. We can define our functions using the "fn" keyword.

Syntax.

fn function_name()
{
//function body code goes here
}

We have seen the syntax of the function. Now, let's understand functions using an example.

Example.

fn add(x: i32, y: i32) -> i32 {
    x + y
}

In this example, we create a function named "add" which takes two integer arguments named x and y and returns their sum as an integer. The -> specifies that this function returns something, and i32 denotes the return type as an integer.

To know more about functions, refer to this article - How to use Functions in Rust?

Ownership and Borrowing in Rust

Rust uses a unique feature that other programming languages do not use, and that is Ownership and Borrowing.

Ownership in Rust

Some languages allow the programmer to manage the memory explicitly, while others use garbage collection. The ownership system in Rust is a set of rules that governs the memory managed at runtime. In Rust, every value has a variable that owns it, and this ownership can be transferred to another variable. This ensures memory safety and data races, which ensures the safe management of memory.

Example

fn main()
{
  let s1 = String::from("Rust");
  let s2=s1;
  println!("s1:{s1}"); // This line will give error as s1 is no longer valid
  println!("s1:{s2}");
}

In the above example, we have created a string variable named s1 and assigned a value to it. In the next line, we have assigned s1 to s2, another variable. The moment we assigned s1 to s2, s1 becomes invalid, and the value can only be accessed from s2. When we try to print the variable s1, it will give an error as it is no longer valid, and its value is now assigned to the variable s2.,

Here, the ownership of s1 is transferred to s2. So, the new owner is s2, and the old owner, s1, is no longer valid.

To know more about ownership, refer to this article - How To Use Ownership In Rust?

Borrowing in Rust

Rust uses borrowing where the ownership is not completely transferred, but only its reference is transferred. As references are immutable and mutable, we can similarly let a variable be borrowed mutably and immutably.

Example.

fn main()
{
    let s1 = String::from("hello"); // s1 owns "hello"
    let s2 = &s1; // s2 references s1, borrows "hello"
    println!("{}", s1);
    println!("{}", s2);
}

In the above example, we have created a variable named s1 and s2. In s1, we have assigned a string "hello"; in s2, we have assigned the immutable reference of  s1. Further, we have printed both s1 and s2. Here, s2 has borrowed the value of s1. As it is an immutable reference, s2 can only read s1 but can not modify it as s2 points to variable s1 and does not directly point to the value "hello" as s1 does. So, the value of s1 is borrowed by s2 as immutable.

To know more about borrowing, refer to this article - How To Use References And Borrowing In Rust?

Cargo Commands in Rust

Cargo is a package manager and builds tool for Rust projects. Cargo refers to the data that a Rust program is designed to handle and process. We can use the cargo command to build, test, and run the project and manage its dependencies. Many cargo commands make our task easy.

Some of them are as follows,

  • Cargo version
  • Cargo new
  • Cargo build
  • Cargo test
  • Cargo run
  • Cargo check
  • Cargo doc

To know more about cargo commands, refer to this article - How To Use Cargo Commands In Rust?

Conclusion

Rust is a powerful system programming language that offers low-level control and high-level abstractions, along with memory safety guarantees that prevent common memory-related bugs. In this article, we've covered some of the key features of Rust, including variables, data types, functions, control flow, ownership, borrowing, and cargo commands. With these features and many more, Rust is a great choice for building high-performance systems.

Frequently Asked Questions (FAQs)

Q. Is Rust easy to learn for beginners?

A. Rust can be challenging for beginners due to its emphasis on safety and memory management. However, with practice and dedication, it is possible to learn Rust and become proficient in using it. Still, avoid using Rust as your first language due to its learning curve.

Q. Can Rust be used for web development?

A. Yes, Rust can be used for web development. Rust has gained popularity in recent years, particularly in the areas of system programming, networking, and web development. Many tech giants, such as Microsoft, Amazon, and Dropbox, have started using Rust in their products and services.

Q. How is Rust different from other programming languages?

A. Rust is a modern system programming language that provides safe and efficient code with a high level of abstraction. Rust is designed to write code for low-level system programming and has a syntax similar to that of C++. Rust also has unique features like crates, traits, ownership, and borrowing.

Q. What are the benefits of using Rust for system programming?

A. Rust provides safe and efficient code with a high level of abstraction, making it a great choice for building high-performance systems. Rust also has unique features like crates, traits, ownership, and borrowing.

Q. Can Rust be used for mobile app development?

A. Rust can be used for mobile app development, particularly for developing performance-critical components. However, Rust is not a mobile app development language in the traditional sense and is not commonly used for building entire mobile applications.


Similar Articles