Operators - ตัวดำเนินการ
std::ops มี traits สำหรับ overload operators เช่น +, -, *, [] และอื่นๆ!
ops คืออะไร?
Section titled “ops คืออะไร?”เมื่อ implement traits เหล่านี้ คุณสามารถใช้ operators กับ types ของคุณได้:
| Operator | Trait | ตัวอย่าง |
|---|---|---|
+ | Add | a + b |
- | Sub | a - b |
* | Mul | a * b |
/ | Div | a / b |
[] | Index | a[i] |
*x | Deref | *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 เพื่อปลดล็อกบทความทั้งหมด
Login with Google