use std::ops::{Add, Mul, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec2 {
pub x: f64,
pub y: f64,
}
impl Vec2 {
pub fn new(x: f64, y: f64) -> Self {
Vec2 { x, y }
}
pub fn abs(self) -> Vec2 {
Vec2 {
x: self.x.abs(),
y: self.y.abs(),
}
}
}
impl Default for Vec2 {
fn default() -> Self {
Vec2 { x: 0.0, y: 0.0 }
}
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, scalar: f64) -> Vec2 {
Vec2 {
x: self.x * scalar,
y: self.y * scalar,
}
}
}
impl std::fmt::Display for Vec2 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Vec2(x={}, y={})", self.x, self.y)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arithmetic_and_abs() {
let a = Vec2::new(3.0, -4.0);
let b = Vec2::new(1.0, 2.0);
assert_eq!(a + b, Vec2::new(4.0, -2.0));
assert_eq!(a - b, Vec2::new(2.0, -6.0));
assert_eq!(a * 2.0, Vec2::new(6.0, -8.0));
assert_eq!(a.abs(), Vec2::new(3.0, 4.0));
assert_eq!(Vec2::default(), Vec2::new(0.0, 0.0));
assert!(format!("{}", a).contains("Vec2(x="));
}
}