Rust Programming Language Tutorials and Example

Rust featured image

Rust:

Rust is an expression-based programming language developed by Mozilla.

Why one more programming language ?

When mozilla planned for rust browser, it tried to use the C++ but eventhough C++ is historically been a great language, if you put a security in front, then we can not proceed with C++. So Mozilla planned for rust programming language with better security and great speed.

.rs is the extension used for the rust files.

Rust programming language

 

Rust Installation:

You can download the Rust Installation packages here.

 

Command to compile and execute Rust Program:

compile:

rustc file_name.rs

Run:

file_name file_name.rs

Hello World Program:
hello.rs

[plain]

// fn means function and compiler begins its execution always from main()
fn main() {
println!("Hello, world!");
}

[/plain]

 

compile: rustc hello.rs
Run: hello hello.rs

Output:
Hello, world!

Variable Binding:

String s = “javadomain”; [it’s java]
here s is string variable.

But in rust,
let s = “javadomain”;
here let – let statement and used to create the variable binding. foo is the variable binding here.

The above s variable binding is the immutable by default. If you want to change it to mutable then,

let mut s = “Javadomain”;
Eg:
let google_rank = 1; // immutable.
let mut google_rank = 1; // mutable

String in Rust:

let mut siteName = String::new();

siteName is the mutable variable binding with the new String. ::new() refers that it’s a new string and it’s not a instance of any string.

[plain]
fn main() {
// immutable by default
let s = "ngdeveloper.com";
println!("Site name is {}",s);

// mutable
let mut a = "Naveen kumar Gunasekaran";
println!("Author name is {}",&mut a);
}

[/plain]

Output:
Site name is ngdeveloper.com
Author name is Naveen kumar Gunasekaran

 

Comments:

As like other programming languages,

// only used to comment the line.

Import Statements (or) headers:
use std::io;

then we can use the method inside the import directly like this,
io::stdin()

if the import not put on the first line, then we need to use like this,
std::io::stdin()

 

Receiving command line inputs:

[plain]

use std::io;
fn main() {
println!("Enter any number");

// mutable let variable binding with the new String
let mut input = String::new();

// import or header given for stdin.
// read_line takes the mutable string, since the received input string is mutable string.
// read_line returns the io::Result which calls the ok() method which internally calls the expect() when exception occurs.
io::stdin().read_line(&mut input)
.ok()
.expect("Failed to read line");

// printing the user entered number
println!("You have entered: {}", input);
}

[/plain]

Output:
Enter any number
19
You have entered: 19

 

Condition if/else statements:

[plain]
fn main() {
let n = 7;

if n == 10 {
print!("{} is 10", n);
} else if n < 10 {
print!("{} is less than 10", n);
} else {
print!("{} is greater than 10", n);
}
}

[/plain]

output:
7 is less than 10

 

Loop Statements:
for loop:

[plain]

fn main() {
// `n` will take the values: 1, 2, …, 10 in each iteration
// last value is excluded means if it’s 11 then till 10 only loop will run.
for n in 1..11 {
if n % 2 == 0 {
println!("{} is even",n);
} else {
println!("{} is odd", n);
}
}
}

[/plain]

Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
While loop:
fn main() {
let mut n = 1;
while n <= 10 {
if n % 2 == 0 {
println!(“{} is even”,n);
} else {
println!(“{} is odd”, n);
}

// Increment n by 1
n += 1;
}
}
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even:

 

Arrays:

[plain]

fn main() {
// below line throws the error because we initialized the size as 5 but trying to give the 6 values.
//let myArr: [i32; 5] = [1, 2, 3, 4, 5,6];

let myArr: [i32; 5] = [1, 2, 3, 4, 5];

println!("first element of the array is {}", myArr[0]);
}

[/plain]

Output:
first element of the array is 1

 

 

Collections: [HashMap]

Hashmap is key value pair collection.

[plain]

use std::collections::HashMap;

fn main() {
let mut stateCapital = HashMap::new();

stateCapital.insert("Tamilnadu", "Chennai");
stateCapital.insert("Karnataka", "Bangalore");
stateCapital.insert("Maharastra", "Mumbai");
stateCapital.insert("West Bengal", "Kolkata");

// printing the hashmap key and value
for (state, &capital) in stateCapital.iter() {
println!("{}:{}", state,&capital);
}

// removing west bengal from the hashmap
stateCapital.remove(&("West Bengal"));

// printing the hashmap after the removal
for (state, &capital) in stateCapital.iter() {
println!("{}:{}", state,&capital);
}
}

[/plain]

Output:
First time execution:
West Bengal:Kolkata
Karnataka:Bangalore
Tamilnadu:Chennai
Maharastra:Mumbai
Karnataka:Bangalore
Tamilnadu:Chennai
Maharastra:Mumbai
Second time execution:
Tamilnadu:Chennai
Maharastra:Mumbai
West Bengal:Kolkata
Karnataka:Bangalore
Tamilnadu:Chennai
Maharastra:Mumbai
Karnataka:Bangalore

Note: order can not predicted and in each execution order of the elements will be changed.

All the above samples are just to make you understand how rust works!. Read full documention here.

 

 

Leave a Reply