I am learning object oriented programming in Rust. I created my own struct for complex numbers. Could you please review and answer my questions:
Is it possible to implement C++-like default constructor? I want to replace
let c0 = my_math::Complex::default();
withlet c0: Complex;
.Why should I implement
PartialEq
instead ofEq
?Why should I implement
type Output = Complex;
? I already have-> Complex
.
mod my_math {
use std::fmt;
use std::ops;
use std::cmp::PartialEq;
pub struct Complex {
// Complex numbers (real, image * i)
pub real: i32,
pub imaginary: i32
}
impl Complex {
pub fn new(real: i32, imaginary: i32) -> Complex {
Complex {real: real, imaginary: imaginary}
}
}
impl Default for Complex {
fn default() -> Self {
Complex { real: 0, imaginary: 0}
}
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}i)", self.real, self.imaginary)
}
}
impl ops::Add<Complex> for Complex {
type Output = Complex;
fn add(self, rhs: Complex) -> Complex {
Complex {real: rhs.real + self.real, imaginary: rhs.imaginary + self.imaginary}
}
}
impl ops::Sub<Complex> for Complex {
type Output = Complex;
fn sub(self, rhs: Complex) -> Complex {
Complex {real: self.real - rhs.real, imaginary: self.imaginary - rhs.imaginary}
}
}
impl ops::Mul<Complex> for Complex {
type Output = Complex;
fn mul(self, rhs: Complex) -> Self::Output {
Complex {
real: self.real * rhs.real - self.imaginary * rhs.imaginary,
imaginary: self.real * rhs.imaginary + self.imaginary * rhs.real
}
}
}
impl PartialEq for Complex {
fn eq(&self, other: &Self) -> bool {
self.real == other.real && self.imaginary == other.imaginary
}
}
}
fn main() {
let c0 = my_math::Complex::default();
assert!(c0.real == 0);
assert!(c0.imaginary == 0);
let c1 = my_math::Complex{real: 1, imaginary: 10};
let c2 = my_math::Complex::new(2, 20);
let c3 = c1 + c2;
let c3_expected = my_math::Complex::new(3, 30);
assert!(c3 == c3_expected);
println!("{}", c3);
}