Rust Fundamentals -Part 1

Rust Fundamentals -Part 1

Common Concepts in Programming

The content of this post is to make readers understand the fundamentals of rust.

Rust is a statically typed language which means every value in rust will be of some data type. The compiler infers the data type of the variable based on the value assigned to it.

If you're new to rust programming language check out my previous post on rust

Getting Started

Variables And Mutability

Variables

Declaring variables in rust. We use the keyword let to declare a variable followed by it's name and data type.

fn main(){
    let x : i32; // refers x is of type i32
}

Assigning value to a variable. The below example assigns a value to the variable x.

fn main(){
    let x : i32; // refers x is of type i32
    x = 10;
    println!("The value of x is : {}",x); /// This prints 10 
}

Also, we can declare and assign value to a variable in a single line without explicitly giving the data type.

fn main(){
    let x  = 10; // by default  x will of type i32 and stores value 10
    println!("The value of x is : {}",x);
}

Let's see what happens when we try to assign a value to the variable x again.

fn main(){
    let x : i32; // refers x is of type i32
    x = 10;
    x = 20;
    println!("The value of x is : {}",x);
}

This time compiler throws an error:

Screenshot 2022-09-26 at 3.36.14 PM.png

As variables declared in rust are immutable by default. Denoting once a value assigned to a variable cannot be changed unless that variable is mutable. Variables can be made mutable by adding a prefix mut while declaring the variable.

fn main(){
    let mut x : i32; // refers x is of type i32
    x = 10;
    x = 20;
    println!("The value of x is: {}",x);
}

when we run the above example we get the following output.

The value of x is: 20

Constants

Constants are values that are bound to a name and their values are not allowed to change like immutable variables. Constants are declared using the keyword const. Constants cannot be mutated using the keyword mut.

Constants are valid for the entire time a program runs, within the scope they were declared in. This property makes constants useful for values in your application domain that multiple parts of the program might need to know about.

const APPLICATION_NAME : &str = "First Constant";

The above example shows us how constants are declared. Rust’s naming convention for constants is to use all uppercase with underscores between words.

Data Types

As mentioned at the beginning of the post every value in rust is of a certain data type and the data types of all the variables should be known at compile time.

Primitive Data Types

  • Integers
  • Floating Point Numbers
  • Character Type
  • Booleans
  • Tuple
  • Array

Integers

Integers are numbers without fractional components. In rust, integers are signed and unsigned. Signed and Unsigned refers to numbers that either be positive or negative.

  • Signed Integers : i8,i16,i32,i64,i128 these are the types of signed integer which is are 8,16,32,64,128 bit respectively. Each signed integer can store numbers from -(2n - 1) to 2n - 1 - 1 inclusive, where n is the number of bits which the variant uses.

  • Unsigned Integers : u8,u16,u32,u64,u128 these are the types of unsigned integer which are of 8,16,32,64,128 bit respectively. Unsigned variants can store numbers from 0 to 2n - 1.

Floating Point Numbers

Rust has two variants of floating point f32 which is single precision and f64 which are 32 and 64 bits in size. When you declare a floating point number by default it will f64. All the floating points are signed numbers.

fn main(){
  let x = 10.0; // f64 by default
  let y: f32 = 120.0; // variable declared as f32 
}

Character Type

This type is a primitive alphabetic type which used to specify the characters. Characters are defined using single quotes and this type is four bytes in size.

fn main() {
    let ch = 'a';
    let z: char = 'ℤ'; // with explicit type annotation
    let surprised_cat = '🙀';
}

Booleans

Booleans are of one byte in size and have two possible values true and false. This type can also be specified using explicit type annotation bool.

fn main(){
  let  x = true;
  let  y : bool = false;
}

Tuple

Tuples are finite, heterogeneous, sequences. Let's unpack that quickly. First of all, they are finite; this is fairly self-explanatory. They have a size and a fixed number of elements. They are heterogeneous. They can contain multiple different types. This is in contrast to an array, which can only contain elements of the same type. And lastly, they are sequences, meaning they have an order, and most importantly they can be accessed by index (although in a different manner than arrays).

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    println!("The value of tuple is: {:?}",tup);
}

Destructring tuple into variables.

fn main() {
    let tup = (500, 6.4, 1);
    let (x, y, z) = tup;
    println!("The value of z is: {:?}",z);
}

Arrays

Arrays are a homogenous collection of data and are of fixed length. Arrays are useful when you want your data allocated on the stack rather than the heap or when you want to ensure you always have a fixed number of elements. However, arrays are more useful when you know the number of elements will not need to change. Array index in rust starts from 0.

Declaring an array: let name: [type; size] = [elem1, elem2, elem3, elem4];

fn main(){
    let a : [i32;5] = [1,2,3,4,5]; /// here each elements are of i32 size.
    let b = [3;5]; /// This array b will be holding 5 elements with a value of 3
    let last = a[4]; /// accessing last element of array
}

Iterating array elements through indexing:

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

💡 Summary

While learning a programming language it's necessary to know the fundamentals. In this post, we have covered the most basic and necessary programming concepts in rust. The scope of this post is planned to give a quick view of declaring variables, mutating variables and data types. If you find any hardship in understanding any part of this post, please leave a comment so that I can update the content to be more clear. If you like this post please do follow me on Hashnode and subscribe to my newsletter for future updates.

Did you find this article valuable?

Support The Missing Semicolon by becoming a sponsor. Any amount is appreciated!