
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
From and Into Traits in Rust Programming
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:
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 }
Advertisements