Rust – Disambiguating Overlapping Traits
Last Updated :
26 Sep, 2022
In Rust, we have a concept of Overlapping traits. There are many traits that are implemented by a Type and in scenarios where traits require the same name, we introduce a concept of disambiguation of Overlapping Traits.
As we know, trait implementation has its own block. Therefore, the methods of Trait’s get method are known to us during implementation. But confusion arises, when we call the methods simultaneously. To reduce this problem, we have a concept of disambiguation of Overlapping Traits.
Example 1:
Rust
trait NameDisplay
{
fn get(& self ) -> String;
}
trait YearDisplay
{
fn get(& self ) -> u32;
}
struct GFG
{
name: String,
year: u32,
}
impl NameDisplay for GFG
{
fn get(& self ) -> String
{
self .name.clone()
}
}
impl YearDisplay for GFG
{
fn get(& self ) -> u32
{
self .year
}
}
fn main()
{
let geek = GFG
{
name: "GeeksforGeeks" .to_owned(),
year: 2022,
};
let name = <GFG as NameDisplay>::get(&geek);
assert_eq!( "GeeksforGeeks" .to_owned(), name);
let year = <GFG as YearDisplay>::get(&geek);
assert_eq!(2022, year);
}
|
Output:
After this, we create an impl for YearDisplay and NameDisplay respectively. Then, we call the impl YearDisplay and NameDisplay respectively using the get method.
Example 2:
Rust
trait NameDisplay
{
fn get(& self ) -> String;
}
trait YearDisplay
{
fn get(& self ) -> u32;
}
struct GFG
{
name: String,
year: u32,
}
impl NameDisplay for GFG
{
fn get(& self ) -> String
{
self .name.clone()
}
}
impl YearDisplay for GFG
{
fn get(& self ) -> u32
{
self .year
}
}
fn main()
{
let geek = GFG
{
name: "GeeksforGeeks" .to_owned(),
year: 2022,
};
println!( "{}" , geek.get());
let name = <GFG as NameDisplay>::get(&geek);
assert_eq!( "GeeksforGeeks" .to_owned(), name);
let year = <GFG as YearDisplay>::get(&geek);
assert_eq!(2022, year);
}
|
Output:
Explanation:
In this example, we declare two traits – NameDisplay (that has string data type) and YearDisplay(that has unsigned int). Now, in this code, we see have declared two traits – NameDisplay and YearDisplay and a struct GFG. Then, we create a struct GFG. Next, we implement NameDisplay and YearDisplay for the GFG struct. to_owned refers to a clone generalization of borrowed data.
Now, if we use ‘get’ to access geek, then it would throw an error saying that multiple get functions were found which results in an ambiguity. Hence, example 1 is the correct usage of disambiguation overlapping traits.
Share your thoughts in the comments
Please Login to comment...