Skip to content
Justice Tech School

Operator Overloading and Default Methods

Implement std::ops traits such as Add to give + a meaning for your type. Traits can provide default method bodies that implementors may override.

Example
use std::ops::Add;
#[derive(Debug, Clone, Copy)]
struct V { x: i32, y: i32 }
impl Add for V { type Output = V; fn add(self, o: V) -> V { V { x: self.x + o.x, y: self.y + o.y } } }
trait Hello { fn name(&self) -> String; fn hi(&self) -> String { format!("Hi {}", self.name()) } }
struct P;
impl Hello for P { fn name(&self) -> String { "Ada".into() } }
fn main() {
    println!("{:?}", V { x: 1, y: 2 } + V { x: 3, y: 4 });
    println!("{}", P.hi());
}

Result

V { x: 4, y: 6 }
Hi Ada

Exercise

Trait for +.

impl  for V

Quiz Test

Which trait overloads +?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.