Open In App

Rust impl Trait

Last Updated : 08 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads