Operators
Objective: Define class Hundred
. Provide operators that allows for adding numeric values to the instances of Hundred
(on left and right hand side).
Python
class Hundred:
def __radd__(self, other):
return other + 100
def __add__(self, other):
return other + self
print(2 + Hundred()) # 102
print(Hundred() + 4) # 104
print(Hundred() + 4.5) # 104.5
Rust
struct Hundred { } impl std::ops::Add<Hundred> for i32 { type Output = i32; fn add(self, rhs: Hundred) -> i32 { rhs + self } } impl std::ops::Add<i32> for Hundred { type Output = i32; fn add(self, rhs: i32) -> i32 { rhs + 100 } } fn main() { dbg!(2 + Hundred{}); // 102 dbg!(Hundred{} + 4); // 104 // Other numeric types require separate implementation //dbg!(Hundred{} + 4.5 ); }
Note: crate num-traits can help with providing implementation for each numeric type.
Crystal
class Hundred
def +(other)
other + 100
end
end
struct Number
def +(other : Hundred)
other + self
end
end
puts 2 + Hundred.new
puts Hundred.new + 4
puts Hundred.new + 4.5