The IoT Academy Blog

What is Rust Programming Language – Quick Learning Guide!

  • Written By The IoT Academy 

  • Published on February 1st, 2024

Rust is a modern systems programming language developed by the Mozilla Corporation. It is intended to be a language for highly concurrent and highly secure systems. It compiles to native code; hence, it is blazingly fast like C and C++. However, This tutorial for The IoT Academy adopts a simple and practical approach to describe the concepts of Rust programming.

Environment Setup for Rust Programming

Let us learn how to install RUST on Windows.

  • Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on Windows. Download Visual Studio from here, VS 2013 Express.
  • Download and install the Rustup tool for Windows. rustup-init.exe is available for download here, Rust Lang.
  • Double-click the rustup-init.exe file. However, Upon clicking, the following screen will appear.
click-the-rustup-init.exe-file
  • Press enter for default installation. Once installation is completed, The following screen appears.
Press-enter-for-default-installation
  • From the installation screen, it is clear that Rust-related files are stored in the folder

C:\Users\{PC}\.cargo\bin

The contents of the folder are:

cargo-fmt.exe

cargo.exe

rls.exe

rust-gdb.exe

rust-lldb.exe

rustc.exe //This is the compiler for rust

rustdoc.exe

rustfmt.exe

rustup.exe

  • Cargo is the package manager for Rust. Moreover, To verify if cargo is installed, execute the following command:

C:\Users\Admin>cargo -V

cargo 1.29.0 (524a578d7 2018-08-05)

  • The compiler for Rust is rustc. To verify the compiler version, execute the following command:

C:\Users\Admin>rustc –version

rustc 1.29.0 (aa3ca1994 2018-09-11)

First Program Using – Rust

This chapter explains the basic syntax of Rust to learn Rust programming language through a HelloWorld Rust Programming example.

  • Create a HelloWorld-App folder and navigate to that folder on the terminal.

C:\Users\Admin>mkdir HelloWorld-App

C:\Users\Admin>cd HelloWorld-App

C:\Users\Admin\HelloWorld-App>

  • Execute the following command, to create a Rust file.

C:\Users\Admin\HelloWorld-App>notepad Hello.rs

Rust program files have an extension .rs. In addition, The above command creates an empty file Hello.rs, and opens it in Notepad. Add the code given below to this file –

fn

main(){

println!(“Rust says Hello to The IoT Academy !!”);

}

The above program defines a function main fn main(). The fn keyword is used to define a function. However, The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust programming. Generally, It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !.

  • Compile the Hello.rs file using rustc.

C:\Users\Admin\HelloWorld-App>rustc Hello.rs

An executable file (file_name.exe) is generated upon a successful compilation of the program. To verify if the .exe file is generated, execute the following command.

C:\Users\Admin\HelloWorld-App>dir

//lists the files in folder

Hello.exe

Hello.pdb

Hello.rs

  • Execute the Hello.exe file and verify the output.

What is Macro in Rust Programming?

In Rust, macros are like special functions that end with a “!” and, unlike regular functions, they generate code during compilation, giving programs extra capabilities at runtime. They are an advanced version of functions in Rust.

The println! Macro – Syntax

println!(); // prints just a newline

println!(“hello “);//prints hello

println!(“format {} arguments”, “some”); //prints format some arguments

Comments Pattern in Rust

Comments in a program help make it easier to understand. However, They can include extra information like who wrote the code or explanations about functions, but the computer doesn’t pay attention to comments when it’s running the program.

Rust programming supports the following types of comments −

  • In Rust, if you put two slashes “//” in front of some text on a line, the computer will ignore that text—it’s a comment, and only there to help people reading the code.
  • In Rust, if you put /* */ everything in between is treated as a comment. This allows comments to cover multiple lines in the code.

Data Types in Rust

In Rust, the Type System defines the kinds of values the language understands. It checks if the values are right before using them in the program, ensuring the code works correctly. Basically, Rust is statically typed, meaning every value has a specific type, but the computer can figure it out on its own most of the time. This also helps with giving hints in the code and creating documentation automatically.

Scalar Data Types in Rust

In Rust, a scalar type represents just one value, like a number or a character. Rust has four main scalar types.

  • Integer
  • Floating-Point
  • Booleans
  • Characters

We will learn about each type in the next parts.

  • Integer Type

An integer is a whole number without any part, and it’s used to represent whole numbers.

Integers come in two main types: signed and unsigned. Signed integers can hold both negative and positive values, while unsigned integers can only store positive values. A detailed description of integer types is given below:

  • Float Data Type

Rust has two types of float: f32 for single precision and f64 for double precision, with f64 being the default. In fact, Let’s look at an example to learn more about the float data type.

fn main() {

let result=10.00;//f64 by default

let interest:f32=8.35;

let cost:f64=15000.600; //double precision

println!(“result value is {}”,result);

println!(“interest is {}”,interest);

println!(“cost is {}”,cost);

}

  • Boolean Data Type in Rust

Boolean types in programming have two options: true or false. To create a boolean variable, use the keyword bool.

Illustration: 

fn main() {

let isfun:bool = true;

println!(“Is Rust Programming Fun ? {}”,isfun);

}

The output of the above code will be-

Is Rust Programming Fun ? true

  • Character Data Type in Rust

In Rust, the char data type, declared using the char keyword, can represent numbers, alphabets, Unicode, and special characters. It covers a wide range of Unicode characters from U+0000 to U+D7FF and U+E000 to U+10FFFF, not just limited to ASCII.

Let’s look at an example to learn more about the char data type.

fn main() {

let special_character = ‘@’; //default

let alphabet:char = ‘A’;

let emoji:char = ‘😁’;

println!(“special character is {}”,special_character);

println!(“alphabet is {}”,alphabet);

println!(“emoji is {}”,emoji);

}

The output of the above code will be:-

special character is @

alphabet is A

emoji is 😁

Variables in Rust

In Rust, a variable is like a labeled storage box that holds information for a program. Each variable has a specific type, which decides how much space it takes, what kind of values it can store, and what operations can be done with it.

Rules for Naming Variables

In this section, we will learn about the different rules for naming a variable.

  • You can name a variable in Rust using letters, numbers, and underscores.
  • In Rust, a variable name has to start with a letter or an underscore.
  • Uppercase and lowercase letters are different, and this matters because Rust pays attention to the case of letters – it’s case-sensitive.

Syntax: You don’t have to specify the data type when making a variable in Rust. The type is figured out from the value you give to the variable.

To declare a variable in Rust, you use the following syntax:

let variable_name=value;// no type specified

let variable_name:dataType = value; //type specified

Constants in Rust Programming

Constants in Rust are like values that stay the same; once you declare one, its value can’t be altered. To declare a constant, use the keyword “const,” and it needs to have a specific type. Here’s the syntax:

const VARIABLE_NAME:dataType=value;

Constants vs Variables

In this section, we will learn about the differentiating factors between constants and variables.

  • In Rust, you declare constants with “const” and variables with “let.”
  • When you create a variable, you don’t have to say what kind of information it will store. But if you make something constant, you must say what type of information it will always have. So, saying const USER_LIMIT=100 without mentioning the type would cause an error.
  • When you use “let” to create a variable, it’s normally unchangeable. But if you want to change it, you can add “mut” before it. On the other hand, constants are always unchangeable.
  • Constants can only be assigned a value that’s fixed and known in advance, like a simple calculation, and not something that depends on running a function or figuring out a value during the program’s execution.
  • Constants can be announced in any part of the code, even outside specific functions or areas, which is helpful when many parts of the code should use the same value.

String in Rust

The String data type in Rust can be classified into the following –

  • String Literal (&str)
  • String Object (String)

Operators in Rust

Rust programming uses operators like a tool that does something to information. The things it works on are called operands, which are the data it uses.

The major operators in Rust can be classified as,

  • Arithmetic
  • Bitwise
  • Comparison
  • Logical
  • Bitwise
  • Conditional

Loops In Rust

Rust provides different types of loops to handle looping requirements:

  • while
  • loop
  • for

1. Definite Loop

A definite loop has a set and a known number of repetitions. However, The for loop is an example of a definite loop.

  • For Loop

The for loop runs a piece of code a certain number of times that you decide. It’s handy for going through a specific list of things, like numbers in an array. The syntax of the for loop is given below.

Syntax:

for temp_variable in lower_bound..upper_bound {

//statements

}

An example of a for loop is shown below

fn main(){

for x in 1..11{ // 11 is not inclusive

if x==5 {

continue;

}

println!(“x is {}”,x);

}

}

2. Indefinite Loops

An indefinite loop is used when you don’t know in advance how many times the loop will run.

Indefinite loops can be implemented using-

  • While: A while loop does something repeatedly as long as a certain condition stays true.

Example:-

fn main(){

let mut x = 0;

while x < 10{

x+=1;

println!(“inside loop x value is {}”,x);

}

println!(“outside loop x value is {}”,x);

}

  • Loop: The loop is a while(true) indefinite loop.

fn main()

{

//while true

let mut x =0;

loop

{

x+=1;

println!(“x={}”,x);

if x==15

  {

break;

  }

}

}

Functions in Rust Programming

Functions are like building blocks for code that’s easy to read and use again. They’re sets of instructions to do a specific job, helping organize the program and making it simpler to understand and update.

When you declare a function, you’re telling the computer the name, what it gives back, and what information it needs. The definition is where you write out the steps it takes.

S.No Name Description

1

Defining a Function

TA function definition specifies what and how a specific task would be done.

2

Calling or invoking a Function

A function must be called to execute it.

3

Returning Function

Functions may also return value along with control, back to the caller.

4

Parameterized Function

Parameters are a mechanism to pass values to functions.

 

Defining a Function

A function definition says what a certain job is and how to do it. You have to define a function before using it. The function body contains the specific steps to perform, and you name functions using the “fn” keyword.

Syntax:

fn function_name(param1,param2..paramN) { 

// function body

}

Invoking a Function

To make a function work, you have to call it, which means you’re making it run. When you call a function, you give it the values it needs to do its job. The function doing the calling is called the caller function.

Syntax:

function_name(val1,val2,valN)

Returning Value from a Function

Functions may also return a value along with control, back to the caller. Such functions are called returning functions.

Syntax: Either of the following syntaxes can be used to define a function with return type.

With return statement

// Syntax1

function function_name() -> return_type

{

//statements

return value;

}

Shorthand syntax without return statement

//Syntax2

function function_name() -> return_type

{

value //no semicolon means this value is returned

}

Function with Parameters

Parameters help send information to functions. They are like a function’s personal details. When you use a function, you provide the necessary values for these details. However, Make sure you give the right number of values, matching the number the function expects.

Parameters can be passed to a function using one of the following techniques –

Pass by Value

When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method do not affect the argument.

Pass by Reference

When you pass parameters by reference, you’re not making a new storage spot; instead, they share the same memory location as the original ones. To do this, you just add an “&” before the variable name.

Array in Rust

An array is like a group of things that are all the same type. It’s just a bunch of similar values that we put together.

Features of an Array

The features of an array are listed below:

  • An array declaration allocates sequential memory blocks.
  • Arrays are static. This means that an array once initialized cannot be resized.
  • Each memory block represents an array element.
  • Array elements are identified by a unique integer called the subscript/ index of the element.
  • Populating the array elements is known as array initialization.
  • Array element values can be updated or modified but cannot be deleted.

Declaring and Initializing Arrays

Use the syntax given below to declare and initialize an array in Rust.

Syntax:

//Syntax1

let variable_name = [value1,value2,value3];

//Syntax2

let variable_name:[dataType;size] = [value1,value2,value3];

//Syntax3

let variable_name:[dataType;size] = [default_value_for_elements,size];

Best Way to Learn Rust

To learn Rust well, begin with the official Rust book, “The Rust Programming Language.” Do exercises, make small projects, and use the Rust playground for hands-on practice. Understand Rust’s ownership system, borrow checker, and fearless concurrency. Join the Rust community, ask questions, and help with open-source projects. Read Rust documentation and watch video tutorials for extra support. 

However, Learn about special features like pattern matching and traits. Practice regularly, get feedback, and improve your projects to strengthen your grasp of Rust’s powerful and safe programming style.

Advantages of Rust Programming

Learning Rust is becoming popular because it has many advantages that make it appealing to developers. Here are some key benefits:

  • Rust’s ownership system makes sure programs are safe by managing memory without needing a garbage collector.
  • It stops common mistakes, like using null pointers or overflowing buffers, which makes programs more secure.
  • It follows clear rules on how data references are shared between threads, making sure concurrent code is reliable.
  • Rust creates code that is safe and runs fast, making it good for things like making games or programming at a system level.
  • It allows developers to use high-level abstractions without incurring a runtime performance cost.
  • Rust lets developers build apps for different systems using one set of code. This makes it easy to create software that works smoothly on many operating systems.

Rust combines memory safety, performance, and a supportive community, making it a compelling choice for developers who prioritize writing efficient and reliable code.

Drawbacks of Rust Programming

While Rust is a powerful and popular programming language, it is not without its disadvantages. Here are some potential drawbacks of using Rust:

  • Rust can be harder to learn than some other languages because it uses a system to manage memory which might be tough for new developers.
  • The Rust code may be frustrating, especially for those used to languages that handle memory automatically.
  • Sometimes it needs more lines of code for the same tasks as compared to Python or JavaScript.
  • Rust’s collection of tools and libraries is getting bigger, but it’s not as vast as languages like Python or Java. This might be a limitation when looking for specific tools or libraries.
  • Rust is known for taking more time to compile than some other languages, which can be a drawback, especially for big projects during development.

Even though Rust has some downsides, many developers like it for being fast and ensuring memory safety. Deciding to use Rust depends on what the development team likes and what the project needs.

Conclusion

In conclusion, Rust programming is a modern language by Mozilla, that emphasizes high concurrency and security. This guide helps set up Rust on Windows and covers key concepts, data types, and features like its ownership system. Rust’s strengths include safety, performance, and a supportive community, but it may pose challenges like a learning curve and verbose syntax. However, Choosing Rust depends on personal preferences, project needs, and team familiarity, so weighing the pros and cons is vital in software development.

Frequently Asked Questions
Q. Is Rust a hard coding language?

Ans. Yes, Rust can be tough for beginners because it focuses on keeping your code safe and efficient with complex concepts. Once you get the hang of it, though, its strict rules help you write better and safer code for system-level programming.

Q. Is Rust C++?

Ans. Rust is a bit like C++, both are system programming languages controlling memory. However, Rust focuses on safety with a tool called a borrow checker, stopping common mistakes. Rust has modern syntax, and a strong ownership system, and avoids some issues found in C++, making it safer and better for handling multiple tasks at the same time.

Q. What is the difference between Rust vs Python?

Ans. Rust is for low-level tasks, focusing on speed and safety. Python is for general use, like web development and data analysis, prioritizing simplicity over top performance. They serve different needs in programming.

About The Author:

The IoT Academy as a reputed ed-tech training institute is imparting online / Offline training in emerging technologies such as Data Science, Machine Learning, IoT, Deep Learning, and more. We believe in making revolutionary attempt in changing the course of making online education accessible and dynamic.

logo

Digital Marketing Course

₹ 9,999/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 29,999/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp