Rust - From and Into Traits
Last Updated :
09 Nov, 2022
In Rust, we have the From and Into Traits that are linked internally and are implemented in type, conversion scenarios say in scenarios where we convert from type A to type B.
The syntax for From Trait:
impl trait From<T>
{
fn from(T) -> Self;
}
From traits in Rust are mainly used for evaluating value conversions while taking input from users. From Traits is preferred over Into Traits due to the fact that From Traits because From Trait provides an implementation of Into function from its standard library.
From Trait is extremely helpful in error handling i.e. when a function call fails, the return type of the function of the form Result<T, E>. The From trait in these situations is extremely helpful as it handles the function by allowing us to return a single error type which in turn encapsulates several error types.
The From Trait in rust helps us define a type from oneself to another. Its most common type is the conversion between primitive and other data types.
In this example, we define a _my_str variable and assign a value "GeeksforGeeks". Before proceeding, we need to import the std::convert::From before converting the str into a String.
Example 1:
Rust
// Rust program for From Traits
use std::convert::From;
fn main() {
let _my_str = "GeeksforGeeks";
// converting an str into a String
let _my_string = String::from(_my_str);
}
Output:
In the given below example, we define a struct that has a 'year' value defined by the i32 type. We use the impl function for the GFG struct that takes the GFG struct and the item value is passed onto it. After we define the main function, we let a variable num declare into the GFG struct (we pass 2022 value) using From trait.
As we see, the value of num gets passed here, and the output gets printed.
Example 2:
Rust
// Rust program for From Trait
use std::convert::From;
#[derive(Debug)]
struct GFG {
year: i32,
}
impl From<i32> for GFG {
fn from(item: i32) -> Self {
GFG {year: item }
}
}
fn main() {
let num = GFG::from(2022);
println!("learning Rust from {:?}", num);
}
Output:
Into Trait:
The Into trait is just the opposite of From Trait. Once we have implemented the From Trait for our type, Into Trait is called when necessary. The into Trait requires certain specifications as we require certain specifications to convert as the compiler is not able to differentiate most of the time. Into Trait is mainly used in specifying trait bounds for generic functions that in turn ensure specific types are converted via the Into Trait.
Example 3:
Rust
// Rust program for Into Trait
use std::convert::From;
#[derive(Debug)]
struct GFG {
year: i32,
}
impl From<i32> for GFG {
fn from(item: i32) -> Self {
GFG { year: item }
}
}
fn main() {
let int_var = 2022;
let num: GFG = int_var.into();
println!("Learning Rust from {:?}", num);
}
Output:
In this example, we first implement the std::convert::From function for the implementation of the Into Trait. We define a struct and use impl to pass it to the function. But this time, instead of assigning a new variable, we use the .into() method that is implemented from the std::convert::from.
Similar Reads
Rust - ToString and FromStr Trait
Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. In this article, we will see the concept of ToString and FromStr Trait. ToString Trait:We can conve
2 min read
Rust - Drop Trait
Drop trait lets us customize what happens when a value is about to go out of scope. Drop trait is important to the smart pointer pattern. Drop trait functionality is used when implementing a smart pointer. For example, Box<T> customizes Drop to deallocate the space on the heap that the box po
3 min read
Rust - Generic Traits
Rust is an extremely fast programming language that supports speed, concurrency, as well as multithreading. In Rust, we have a concept of Generic Traits where Generics are basically an abstraction of various properties, and Traits are basically used for combining generic types for constraining types
2 min read
Rust - Iterator Trait
Rust is a systems programming language focusing on speed, concurrency, and ensuring safe code. The iterator trait in Rust is used to iterate over Rust collections like arrays. Syntax: //pub refers to the trait being declared public pub trait Iterator { // type refers to the elements type over which
3 min read
Rust - Clone Trait
In Rust, we have a concept of clone trait. Clone traits have the ability to duplicate objects explicitly. We can make anything copy with the Clone Trait. Syntax: //pub refers to public trait pub trait Clone {Â Â fn clone(&self) -> Self; Â Â fn clone_from_trait(&mut self, source: &Self)
2 min read
Rust - Deref Trait
Deref<T> trait in Rust is used for customizing dereferencing operator (*) behavior. Implementing the Deref <T> treats the smart pointer as a reference. Therefore, any code that references the deref trait would also refer to smart pointers. Regular References in Deref Trait:Regular refer
2 min read
Rust - Traits
A trait tells the Rust compiler about functionality a particular type has and can share with other types. Traits are an abstract definition of shared behavior amongst different types. So, we can say that traits are to Rust what interfaces are to Java or abstract classes are to C++. A trait method is
8 min read
Rust Types and Inference
Pre-requisites: Rust, Scalar Datatypes in Rust Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. In this article, we will focus on Rust's primitive t
12 min read
Rust impl Trait
In Rust, there is a concept of impl trait. Â impl Trait is used to implement functionality for types and is generally used in function argument positions or return positions. It is used in scenarios where our function returns a single type value. In the impl trait, we always specify the impl keyword
2 min read
Rust - For and Range
Suppose you have a list of items and you want to iterate over each item in the list. One thing we can do is use a for loop. Using a for loop, we can iterate over a list of items. In Rust, we use the keyword for in followed by the variable name or the range of items we want to iterate over. Let's see
4 min read