Open In App

Rust – Concept of Associated Items and Associated Type

Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of associated items and associated types. Associated items use the type keyword while associated type uses type alias and functions for their implementation. 

Associated Items in Rust:

Rust uses certain items and declares them in their traits or defines them while implementing them. These are known as associated items. Whenever we declare a module, there are associated items present that are generally present as subsets. They are helpful in scenarios when associated items require them logically relate to them. Associated items basically define a certain set of rules that is applied to trait generics over defining new items inside it. Associated type items are generally of two types: one where there is an actual implementation of the definitions and the other that has declarations defined for definitions.
 

In associated items, there is a concept of associated functions and methods that associate functions with type and declares the signature for associated function types. Generally, associated functions have an identifier with them that is the same as that of the name of the function, and the generics, parameters, and return types should be the same as that of the function declaration.

Example 1:

Rust




// Rust code
#![allow(unused)]
fn main() {
trait Number {
   fn from_i32(num: i32) -> Self;
}
 
impl Number for f64 {
   fn from_i32(num: i32) -> f64 { num as f64 }
}
 
let var: f64 = Number::from_i32(42);
let var: f64 = <_ as Number>::from_i32(42);
}


Output:

 

Explanation: 

In this example, we have associated a trait declaration, and the path is declared to the trait so that during the run time the Trait gets substituted by the impl Number trait. Here, Number is declared as a Trait, and the Number trait is implemented for the f64 type using _i32 and passing num as f64. We have declared var as an f64 and then we import the Number from _i32 type and pass 42 in it.

Associated Type:

Associated types in Rust are used for improving the code readability overall. This is done by moving the inner types trait locally into output types. Associated types are mainly used for connecting various placeholders to traits so that the trait methods can use the placeholder types as format specifiers. The trait implementer uses the types in this manner and without knowing the nature of types, the traits are implemented.

Example 2:

Rust




// Rust code
struct GfgContainer(i32, i32);
 
trait HasItems {
    
    type X;
    type Y;
 
    fn items(&self, _: &Self::X, _: &Self::Y) -> bool;
    fn first_func(&self) -> i32;
    fn second_func(&self) -> i32;
}
 
impl HasItems for GfgContainer {
  
    type X = i32;
    type Y = i32;
 
    fn items(&self, num_one: &i32, num_two: &i32) -> bool {
        (&self.0 == num_one) && (&self.1 == num_two)
    }
    
    fn first_func(&self) -> i32 { self.0 }
 
 
    fn second_func(&self) -> i32 { self.1 }
}
 
fn multiply<C: HasItems>(item: &C) -> i32 {
    item.second_func() * item.first_func()
}
 
fn main() {
    let num_one = 50;
    let num_two = 20;
 
    let item = GfgContainer(num_one, num_two);
 
    println!("1st number: {}", item.first_func());
    println!("2nd number: {}", item.second_func());
     
    println!("Multiplied value: {}", multiply(&item));
}


Output:

 

Explanation:

In this example, we have declared a trait GfgContainer that basically checks whether 2 items are stored inside of the HasItem trait. It retrieves the first_func and the second_func values. Next, we have defined a trait HasItems that has the generic types through which first_func and second_func methods are utilized. In the HasItems trait, there is an item method where we pass the types X and Y which has both i32 types. We grab the values of the first_func and the second_func by using the self keyword in which self.) is the first number and self.1 is the second number. finally, we define the multiply function through which we pass the item. first_func and the item.second_func and the values of the functions are assigned from the main function.



Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads