Rust Smart pointers

let us look at Rust smart pointers examples. Smart pointers like Box help save the heap information of an object.

fn main() {
   let y = 7;

   let z = Box::new(y);

   println!("{}",7==y);
   println!("{}",7==*z);

}

The code above is compiled using the below command.

apples-MacBook-Air:iterators bhagvan.kommadi$ rustc smartpointers.rs

The output will be as below:

apples-MacBook-Air:smartpointers bhagvan.kommadi$ ./smartpointers
true
true

Rust 1.50.0 Features

Language

  •     You can now use const values for x in [x; N] array expressions. This has been technically possible since 1.38.0, as it was unintentionally stabilized.
  •     Assignments to ManuallyDrop<T> union fields are now considered safe.

Compiler

  •     Added tier 3* support for the armv5te-unknown-linux-uclibceabi target.
  •     Added tier 3 support for the aarch64-apple-ios-macabi target.
  •     The x86_64-unknown-freebsd is now built with the full toolset.
  •     Dropped support for all cloudabi targets.
  •     Refer to Rust’s platform support page for more information on Rust’s tiered platform support.

Libraries

  •     proc_macro::Punct now implements PartialEq<char>.
  •     ops::{Index, IndexMut} are now implemented for fixed sized arrays of any length.
  •     On Unix platforms, the std::fs::File type now has a “niche” of -1. This value cannot be a valid file descriptor, and now means Option<File> takes up the same amount of space as File.

Stabilized APIs

  •     bool::then
  •     btree_map::Entry::or_insert_with_key
  •     f32::clamp
  •     f64::clamp
  •     hash_map::Entry::or_insert_with_key
  •     Ord::clamp
  •     RefCell::take
  •     slice::fill
  •     UnsafeCell::get_mut

The following previously stable methods are now const.

  •     IpAddr::is_ipv4
  •     IpAddr::is_ipv6
  •     Layout::size
  •     Layout::align
  •     Layout::from_size_align
  •     pow for all integer types.
  •     checked_pow for all integer types.
  •     saturating_pow for all integer types.
  •     wrapping_pow for all integer types.
  •     next_power_of_two for all unsigned integer types.
  •     checked_power_of_two for all unsigned integer types.

Cargo

  •     Added the [build.rustc-workspace-wrapper] option. This option sets a wrapper to execute instead of rustc, for workspace members only.
  •     cargo:rerun-if-changed will now, if provided a directory, scan the entire contents of that directory for changes.
  •     Added the –workspace flag to the cargo update command.

Misc

  •     The search results tab and the help button are focusable with keyboard in rustdoc.
  •     Running tests will now print the total time taken to execute.

Rust borrowing

let us look at Rust borrowing examples. Borrowing is related to transfer of control of variable or value from one function to another temprorarily.

fn main(){
   let vector = vec![11,21,32];
   show_vector(&vector);
   println!("{}",vector[0]);
}
fn show_vector(x:&Vec<i32>){
   println!("Inside print_vector function {:?}",x);
}

The code above is compiled using the below command.

apples-MacBook-Air:iterators bhagvan.kommadi$ rustc borrowing.rs

The output will be as below:

apples-MacBook-Air:borrowing bhagvan.kommadi$ ./borrowing 
Inside print_vector function [11, 21, 32]
11

Rust Iterators

let us look at Rust iterators examples.

fn main() {

   let arr = [11,12,13,14];

   let iterator = arr.iter();
   for data in iterator{
      print!("{}\t",data);
   }

   print!("\n");
}

The code above is compiled using the below command.

apples-MacBook-Air:iterators bhagvan.kommadi$ rustc iterator.rs

The output will be as below:

apples-MacBook-Air:iterators bhagvan.kommadi$ ./iterator
11	12	13	14

Rust Enums

let us look at Rust enum examples.

#[derive(Debug)]
enum Gender {
   Male,Female,Trans
}
fn main() {
   let male_gen = Gender::Male;
   let female_gen = Gender::Female;
   let trans_gen = Gender::Trans;

   println!("{:?}",male_gen);
   println!("{:?}",female_gen);
   println!("{:?}",trans_gen);
}

The code above is compiled using the below command.

rustc enum.rs

The output will be as below:

apples-MacBook-Air:enum bhagvan.kommadi$ rustc enum.rs
apples-MacBook-Air:enum bhagvan.kommadi$ ./enum
Male
Female
Trans

Rust Arrays

let us look at Rust array examples.

fn main(){
   let arry:[i32;4] = [90,21,30,40];
   println!("array values are {:?}",arry);
   println!("array length is :{}",arry.len());
}

The code above is compiled using the below command.

rustc array.rs

The output will be as below:

apples-MacBook-Air:array bhagvan.kommadi$ rustc array.rs
apples-MacBook-Air:array bhagvan.kommadi$ ls
array array.rs
apples-MacBook-Air:array bhagvan.kommadi$ ./array
array values are [90, 21, 30, 40]
array length is :4

Rust Tuples

let us look at Rust tuples examples.

fn main() {
   let tuple:(i32,f64,u8) = (-225,5.9,32);
   println!("{:?}",tuple);
   println!("integer value is :{:?}",tuple.0);
   println!("float value is :{:?}",tuple.1);
   println!("unsigned integer value is :{:?}",tuple.2);
}

The code above is compiled using the below command.

rustc tuples.rs

The output will be as below:

apples-MacBook-Air:tuple bhagvan.kommadi$ rustc tuples.rs
apples-MacBook-Air:tuple bhagvan.kommadi$ ./tuples
(-225, 5.9, 32)
integer value is :-225
float value is :5.9
unsigned integer value is :32

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

~          

~