Open In App

Rust – Operator Overloading

Last Updated : 06 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of operator overloading. This is generally performed by Traits. For making use of operator overloading, we import core::ops in Rust. Core:: ops is a module in Rust that allows the traits to overload the operators in our code. By default, most of the traits are automatically imported in Rust, but certain operators that are only supported by traits are overloaded. Therefore, by implementing the traits we overload the operators. Example: Add Trait in Rust.

Example 1:

Rust




// Rust program for Operator Overloading
use std::ops;
struct Courses;
struct GFG;
  
#[derive(Debug)]
struct GFGCourses; 
  
#[derive(Debug)]
struct GFGPractice; 
  
impl ops::Add<GFG> for Courses {
    type Output = GFGCourses;
  
    fn add(self, _rightside: GFG) -> GFGCourses {
        println!("GFGCourses gets called");
  
        GFGCourses
    }
}
  
// Rust operator 
impl ops::Add<Courses> for GFG {
    type Output = GFGPractice;
  
    fn add(self, _rightside: Courses) -> GFGPractice {
        println!("GFGPractice gets called");
  
        GFGPractice
    }
}
  
// Print result
fn main() {
    println!("Buying {:?} from Geeks for Geeks website", Courses + GFG);
    println!("Practicing {:?} from Geeks for Geeks website", GFG + Courses);
}


Output:

 

Explanation:

In this example, we have declared two structs – Courses and GFG. Before writing the program, we need to module std::ops for loading the packages and modules. Using the std::ops trait we add the two traits. Here, we use Add<GFG> for the addition of the GFG type by using a variable (_rightside) so that we could declare the operation Courses + GFG = CoursesGFG.

Next, we reverse the struct types and try to add via a non-communicative addition method. For this case, we use Add <Courses> and similarly assign a _rightside variable for adding the trait with the ‘Course’ type. The two blocks in this example demonstrate the example of the time when we called GFGPractice and GFGCourses. Lastly, the traits are called from the main function again with the print statements respectively.


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

Similar Reads