Skip to content
เข้าสู่ระบบ

Ops Structs

Operator overloading structs และ traits ใน Rust ช่วยให้ custom types ใช้ operators มาตรฐานได้เหมือน built-in types เช่น +, -, *, [] ผ่าน traits ใน std::ops module

Arithmetic operators (+, -, *, /, %) สามารถ overload ได้ผ่าน traits Add, Sub, Mul, Div, Rem ทำให้ custom types เช่น vectors, matrices, หรือ complex numbers ใช้ operators เหล่านี้ได้

use std::ops::{Add, Sub, Mul, Div, Rem, Neg};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vector2D {
x: f64,
y: f64,
}
impl Add for Vector2D {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Vector2D {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vector2D {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Vector2D {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Neg for Vector2D {
type Output = Self;
fn neg(self) -> Self::Output {
Vector2D {
x: -self.x,
y: -self.y,
}
}
}
// Scalar multiplication - different RHS type
impl Mul<f64> for Vector2D {
type Output = Self;
fn mul(self, scalar: f64) -> Self::Output {
Vector2D {
x: self.x * scalar,
y: self.y * scalar,
}
}
}
fn main() {
let a = Vector2D { x: 3.0, y: 4.0 };
let b = Vector2D { x: 1.0, y: 2.0 };
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("a + b = {:?}", a + b);
println!("a - b = {:?}", a - b);
println!("-a = {:?}", -a);
println!("a * 2.0 = {:?}", a * 2.0);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด