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

Operators - ตัวดำเนินการ

std::ops มี traits สำหรับ overload operators เช่น +, -, *, [] และอื่นๆ!

เมื่อ implement traits เหล่านี้ คุณสามารถใช้ operators กับ types ของคุณได้:

OperatorTraitตัวอย่าง
+Adda + b
-Suba - b
*Mula * b
/Diva / b
[]Indexa[i]
*xDeref*ptr
use std::ops::Add;
#[derive(Debug, Copy, Clone)]
struct Point { x: i32, y: i32 }
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let sum = p1 + p2;
println!("{:?} + {:?} = {:?}", p1, p2, sum);
}

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

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