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 and the associated trait name. In the function body, the methods are called on the impl item. In the impl trait, string or i32 types do not get compiled. The impl trait syntax was designed to improve code readability.
Impl trait finds its usage in two types:
In Scenarios Requiring Argument Type:
Syntax:
// Scenario requiring argument type
fn GFG<B: Debug>(a: B) {
dbg!(a);
}
Example 1:
Rust
#![allow(unused)]
fn main() {
fn mult_of_integers(elements: impl Iterator<Item = u32>) -> u32 {
let mut mult = 10;
let mut x = 1;
for int in elements {
mult = mult * x;
println!(" value of mult: {} for x:{}",mult,x);
x=x+1;
}
mult
}
mult_of_integers(0..2);
}
Output:
Explanation:
In this example, we have used an impl Trait named and passed it in the function mult_of_integers as an argument. Then, we have declared two mutable variables inside the mult_of_integers function that have been assigned values. Using a for loop to multiply the elements and then returning mult as a part of the return function. Now, when we call the function and pass an iterator, then we get an output that is attached above.
In Scenarios Requiring Return Type:
Example 2:
Rust
#[allow(dead_code)]
fn combining_gfg_vectors(
y: Vec<i32>,
x: Vec<i32>,
) -> impl Iterator<Item=i32> {
y.into_iter().chain(x.into_iter()).cycle()
}
fn main() {
let gfg1 = vec![10,20];
let gfg2 = vec![30, 40];
let mut gfg3 = combining_gfg_vectors(gfg1, gfg2);
assert_eq!(Some(10), gfg3.next());
assert_eq!(Some(20), gfg3.next());
assert_eq!(Some(30), gfg3.next());
assert_eq!(Some(40), gfg3.next());
println!("Operation Successful! Please exit");
}
Output:
Explanation:
In this example, we have declared a function combining_gfg_vectors and then declared two parameters having i32 types x and y. Here, there are two vectors gfg1 and gfg2 that have some elements, and then we have declared another vector gfg3 that basically combines both vectors. Before the impl trait was in use, we had to use iter and importer traits for implementing vector operations. We can clearly see how the impl Trait improves code readability and also asserts the two vectors in a comprehensive fashion.
Similar Reads
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 - 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 - 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 - 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 - 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 - 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