Introduction to Rust programming language

A quick intro to rust programming language

Umer Jamal
5 min readJul 2, 2022

Introduction

Rust is a multi-paradigm, high-level, general-purpose programming language designed for performance and safety, especially safe concurrency.

Rust code uses snake case as the conventional style for function and variable names.

Why use Rust???

Rust is most loved programming language 5 years in a row on stack overflow survey. Developers of rust came up with concepts that made it easy to create memory safe projects with the performance of c and developers are loving it. Big players like Discord, Figma, Microsoft, Google, Dropbox are using rust.

Rust is a fast and memory safe general purpose programming language designed for performance and safety created by Mozilla. Rust looks something similar to C++ but includes a borrow checker.

The unifying principles behind Rust are:

  • Strictly enforcing safe borrowing data.
  • functions, methods and closures to operate on data.
  • tuples, structs and enums to aggregate data.
  • patter matching to select and destructure data.
  • traits to define behaviour on data.

Installing Rust on your system

Install rustup — Rust toolchain

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

Verify installation using

rustc --version

You can follow this this link for your operating system.

Getting started

we need to understanding some of the basics of Rust. I have added the link to the Rust book pages if you want to read more about any topic.

Basics Data types in Rust

Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. Integers are u8,u32, i32, i64, usize, and the list goes on here basically u prefix suggests that we have an unsigned integer and the suffix number tell the number of bits. So u8 is an unsigned 8-bit number(0 to 255).

Length Signed Unsigned
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize

We have f32 and f64 for floating-point numbers. bool for booleans, and char for characters. Rust has 2 types for strings, str and String. String is a growable, heap-allocated data structure. str is an immutable fixed-length string somewhere in memory.

Read more on Rust book.

Creating a variable and mutability

We can create a variable with the let keyword

// The compiler identifies the Rvalue as i32, so it sets the type of variable to i32 let a=0;

we can also set the data type for a variable, eg.

let a :u8 = 0;

In Rust, all the variables are immutable by default. Which means their value can not be changed once set. And here comes the mut keyword. We can initialize the variable with let mut to have a mutable variable. eg.

// This program will compile
let mut a = 0;
a=a+1;
a=100;

Control flow

We can use if else statement in Rust just like we can do in other language, here is a small program for us to understand the syntax.

fn main(){
let a=99;
if a%2==0{
println!("Even");
}
else{
println!("Odd");
}
}

We also have loops in Rust. We can create a loop with 3 keywords loop, for, and while. Since for is most common. Here is an example of it. You can checkout example for loop and while here.

fn main() {
for i in 0..7 { // 0..7 is range expression including 0 excluding 7.
println!("variable `i` is : {}", i);
}
}

Functions and Macros

Function definitions in Rust start with fn and have a set of parentheses after the function name. The curly brackets tell the compiler where the function body begins and ends.

fn main() {
another_function(5);
another_function_with_x_and_y(1,2);
}
fn another_function(x: i32) {// input paramter and type
println!("The value of x is: {}", x);
}
fn another_function_with_x_and_y(x: i32,y:i32) {
println!("The value of x is: {} {}", x, y);
}

For this tutorial, we can assume macros are also functions. They end with !, like println! macro, format! macro, and msg! macro.

Enums and the match syntax

Rust has enums. They are more than simple enums other languages provide. In Rust, we can even store data in the enums. Here is the example of Result enum. We are going to make use of the Result enum in our program.

// Here the pub keyword means it is public.
// We have used generics T and E for data and error type
pub enum Result<T, E> {
Ok(T),
Err(E),
}

Here is an enum and match example with an explanation of each line:

enum Coin {
Penny,
Nickel,
Dime,
Custom(i32),
}
// Creating a coin enums
// notice how some values have no parameter
// and how we can have an i32 value stored in `Custom`

let coin=Coin::Custom(30);
let coin2 =Coin::Nickel;
// We can create instances like this

let a = match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Custom(e) => e,
};
// We can use the match syntax to know what type of coin we have // and set a corresponding value to the variable `a`. assert_eq!(a,30); // In this case a will be equal to 30 because coin is Custom with value 30.

Arrays and Slices

All static type language have arrays, which are stream of values stored linearly in memory and indexed from zero.

fn main() {
let arr: [i32, 5] = [1, 2, 3, 4, 5];
for i in 0..5 {
println!("{}", arr[i]);
}
}

Slices are used often over arrays in rust. Slices are reference pointing to arrays. They behave like arrays and Slices let you reference a contiguous sequence of elements in a collection rather than the whole collection. so it does not have ownership.

fn print_values(values: &[i32]) {
for i in 0..values.len() {
println!("{}", i);
}
}fn main() {
let arr = [1, 2, 3, 4];
print_values(&arr);
}

Vectors

Vector is a collection type Vec<> that is used to store collection of a type. Like array vector allow to store more that one value that puts the value of same type to each other in memory. To create a vector call Vec::new or use vec! macro.

let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];

To store values in vector call push() method.

let mut v = Vec::new();v.push(1);
v.push(2);

To get values in vector call get(index) method.

if let Some(value) = v.get(2) {
println!("{}", value);
}

Iterate over vector

let v = vec![1, 2, 3, 4];for i in &v {
println!("{}", i);
}

Ownership Concept

Ownership concept is new and unique concept and useful concept because it killed the need of garbage collection. It enables developers to write memory safe code. Ownership is a set of rules that determines how program is going to manage memory.

Ownership rules.

  • Each value has a variable that’s called it’s owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

let connect on LinkedIn

--

--

Umer Jamal

Senior Software Engineer | MERN stack | web 3.0 | Smart contract developer | Smart contract auditor | Blockchain developer.