Ops Traits
Operator overloading traits ใน Rust ช่วยให้ custom types ใช้ operators ได้เหมือน built-in types traits เหล่านี้อยู่ใน std::ops module และเป็นพื้นฐานของ ergonomic API design
1. Add, Sub, Mul, Div
Section titled “1. Add, Sub, Mul, Div”Arithmetic operator traits พื้นฐานสำหรับ binary operations โดยแต่ละ trait มี associated type Output ที่กำหนด return type
Basic Arithmetic Implementation
Section titled “Basic Arithmetic Implementation”use std::ops::{Add, Sub, Mul, Div};
#[derive(Debug, Clone, Copy)]struct Point { x: f64, y: f64,}
impl Add for Point { type Output = Point;
fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } }}
impl Sub for Point { type Output = Point;
fn sub(self, other: Point) -> Point { Point { x: self.x - other.x, y: self.y - other.y, } }}
// Scalar multiplication - different RHS typeimpl Mul<f64> for Point { type Output = Point;
fn mul(self, scalar: f64) -> Point { Point { x: self.x * scalar, y: self.y * scalar, } }}
impl Div<f64> for Point { type Output = Point;
fn div(self, scalar: f64) -> Point { Point { x: self.x / scalar, y: self.y / scalar, } }}
fn main() { let p1 = Point { x: 1.0, y: 2.0 }; let p2 = Point { x: 3.0, y: 4.0 };
println!("p1 + p2 = {:?}", p1 + p2); println!("p2 - p1 = {:?}", p2 - p1); println!("p1 * 2.0 = {:?}", p1 * 2.0); println!("p2 / 2.0 = {:?}", p2 / 2.0);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google