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.
Let us learn how to install RUST on Windows.
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 |
C:\Users\Admin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) |
C:\Users\Admin>rustc –version rustc 1.29.0 (aa3ca1994 2018-09-11) |
This chapter explains the basic syntax of Rust to learn Rust programming language through a HelloWorld Rust Programming example.
C:\Users\Admin>mkdir HelloWorld-App C:\Users\Admin>cd HelloWorld-App C:\Users\Admin\HelloWorld-App> |
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 – !.
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 |
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 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, 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.
In Rust, a scalar type represents just one value, like a number or a character. Rust has four main scalar types.
We will learn about each type in the next parts.
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:
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 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 |
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 😁 |
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.
In this section, we will learn about the different rules for naming a variable.
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 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; |
In this section, we will learn about the differentiating factors between constants and variables.
The String data type in Rust can be classified into the following –
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,
Rust provides different types of loops to handle looping requirements:
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.
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-
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); } |
fn main() { //while true let mut x =0; loop { x+=1; println!(“x={}”,x); if x==15 { break; } } } |
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 } |
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.
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:
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]; |
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.
Learning Rust is becoming popular because it has many advantages that make it appealing to developers. Here are some key benefits:
Rust combines memory safety, performance, and a supportive community, making it a compelling choice for developers who prioritize writing efficient and reliable code.
While Rust is a powerful and popular programming language, it is not without its disadvantages. Here are some potential drawbacks of using Rust:
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.
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.
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.
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.
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.
Digital Marketing Course
₹ 9,999/-Included 18% GST
Buy Course₹ 29,999/-Included 18% GST
Buy Course