Rust Generics

Let us look at Rust Generics.  You can start writing Generics in Rust as shown below:

 

struct Val {
val: f64,
}

struct GenVal<T> {
gen_val: T,
}

// impl of Val
impl Val {
fn value(&self) -> &f64 {
&self.val
}
}

// impl of GenVal for a generic type `T`
impl<T> GenVal<T> {
fn value(&self) -> &T {
&self.gen_val
}
}

fn main() {
let x = Val { val: 3.0 };
let y = GenVal { gen_val: 3i32 };

println!("{}, {}", x.value(), y.value());
}

 

The code above is compiled using the below command.

rustc generic_example.rs

 

The output will be as below:

apples-MacBook-Air:generics bhagvan.kommadi$ ls

generic_example generic_example.rs

apples-MacBook-Air:generics bhagvan.kommadi$ ./generic_example

5, 6

apples-MacBook-Air:generics bhagvan.kommadi$

Rust IO

Let us look at Rust IO. To read a file.

use std::io::Read;

fn main(){

   let mut file = std::fs::File::open("input.txt").unwrap();

   let mut contents = String::new();

   file.read_to_string(&mut contents).unwrap();

   print!("{}", contents);

}


 

The code above is compiled using the below command.

 rustc read_file.rs

The output will be as below:

apples-MacBook-Air:io bhagvan.kommadi$ ls

input.txt	read_file	read_file.rs

apples-MacBook-Air:io bhagvan.kommadi$ ./read_file 

line 1

 

Now let us look at the opening a file and writing to a file by adding new line.

use std::fs::OpenOptions;

use std::io::Write;

fn main() {

   let mut file = OpenOptions::new().append(true).open("initial.txt").expect(

      "unable to open file");

   file.write_all("adding new line".as_bytes()).expect("write error");

   file.write_all("\n next line".as_bytes()).expect("write error");

   println!("file adding success");

}

 

The code above can be compiled using :

 rustc append_file.rs

 

The output will be :

apples-MacBook-Air:io bhagvan.kommadi$ ls

append_file initial.txt read_file

append_file.rs input.txt read_file.rs

apples-MacBook-Air:io bhagvan.kommadi$ ./append_file 

file adding success

 

The initial file had :

line 1

 

After the execution of append_file.rs, the new file will be:

 

line 1

adding new line

 next line

~          

~          

 

 

 

 

 

Rust Modules

let us start creating a rust file with the module name as a new module.

 

mod newmodule;

fn method() {
println!("called `method()`");
}

fn main() {
newmodule::method();

method();

newmodule::indirect_access();


}

 

newmodule file is created as shown below:

 

pub fn method() {
println!("called `newmodule::method()`");
}

fn private_method() {
println!("called `newmodule::private_method()`");
}

pub fn indirect_access() {
print!("called `newmodule::indirect_access()`, that\n> ");

private_method();
}


 

The rust module.rs is compiled and the output is as shown below:

apples-MacBook-Air:modules bhagvan.kommadi$ rustc moduleaccess.rs

apples-MacBook-Air:modules bhagvan.kommadi$ ls

moduleaccess moduleaccess.rs newmodule.rs

apples-MacBook-Air:modules bhagvan.kommadi$ ./moduleaccess 

called `newmodule::method()`

called `method()`

called `newmodule::indirect_access()`, that

> called `newmodule::private_method()`

Square Area: Struct & methods

let us look at area of a square  in rust using struct & methods

main.rs

use std::fmt;

struct Square {
    side: i32
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Square of side {}", self.side)
    }
}
impl Square {

fn area(&self) -> i32 {

   let x = self.side;
   x*x
 }
}

fn main() {
    let square = Square { side: 4 };
    println!("{}", square.to_string());
    
     println!("Square area: {}", square.area());
}


Cargo.toml

[package]
name = "rust_square"
version = "0.1.0"
authors = ["bhagvan.kommadi"]
edition = "2018"

[dependencies]

 

Run the following command:

cargo run

 

The screenshot of the output will look like this:

 

rust_square_area

Rust : Get Sum of two numbers

started with Getting the sum of two numbers in rust

main.rs

fn main() {
  let a      = 15;
  let b: i32 = 25;

  let c = get_sum(a,  b);
  println!("a + b = {}", c);
}

fn get_sum(i: i32, j: i32) -> i32 {
  i + j
}

 

Cargo.toml

[package]
name = "rust-sum"
version = "0.1.0"
authors = ["bhagvan.kommadi"]
edition = "2018"

[dependencies]

 

Run the following command:

cargo run

 

The screenshot of the output will look like this:

 

rust_sum