From and Into Traits In Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

From and Into are two traits that Rust provides us. They are internally linked.

From Trait

We make use of From trait when we want to define a trait to how to create itself from any other type. It provides a very simple mechanism with which we can convert between several types.

For example, we can easily convert str into a String.

Example

Consider the example shown below:

 Live Demo

fn main() {
   let my_str = "hello";
   let my_string = String::from(my_str);
   println!("{}",my_string);
}

Output

hello

We can even convert our own types.

Example

Consider the example shown below:

use std::convert::From;
#[derive(Debug)]
struct Num {
   value: i64,
}
impl From for Num {
   fn from(item: i64) -> Self {
      Num { value: item }
   }
}
fn main() {
   let num = Num::from(30);
   println!("My number is {:?}", num);
}

Output

My number is Num { value: 30 }

Into Trait

Into trait is exactly the reciprocal of the From trait, and it generally requires the specification of the type to convert into, as most of the times, the compiler is not able to determine that.

Example

Consider the example shown below:

use std::convert::From;
#[derive(Debug)]
struct Num {
   value: i64,
}
impl From for Num {
   fn from(item: i64) -> Self {
      Num { value: item }
   }
}
fn main() {
   let int = 5;
   let num: Num = int.into();
   println!("My number is {:?}", num);
}

Output

My number is Num { value: 5 }
raja
Published on 03-Apr-2021 12:57:13
Advertisements