Files
LearnRustEasy/src/chapter_3/chapter_3_10_3.md
Davirain 2cabfff8b9 update
2023-05-17 21:27:17 +08:00

1.8 KiB
Raw Blame History

3.10.3 常见的trait

Rust 常见的 trait 包括:

  • std::fmt::Display: 格式化打印用户友好字符串。
  • std::fmt::Debug: 格式化打印调试字符串。
  • std::cmp::PartialEq: 比较值相等。
  • std::cmp::PartialOrd: 比较值顺序。
  • std::cmp::Eq: 类型完全相等关系。
  • std::cmp::Ord: 类型完全顺序关系。
  • std::clone::Clone: 创建类型副本。
  • std::ops::Add: 定义加法操作。
  • std::ops::Mul: 定义乘法操作。
  • std::iter::Iterator: 实现迭代器。

下面分别介绍:

1. std::fmt::Display

use std::fmt;

struct Person {
    name: String,
    age: u32,
}

impl fmt::Display for Person {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ({} years)", self.name, self.age)
    }
}

2. std::fmt::Debug

#[derive(Debug)]
struct Person {
    name: String,
    age: u32,
}

3. std::cmp::PartialEq 和 std::cmp::Eq

#[derive(PartialEq, Eq)]
struct Point {
    x: i32,
    y: i32,
}

4. std::cmp::PartialOrd 和 std::cmp::Ord

#[derive(PartialOrd, Ord)]
struct Point {
    x: i32,
    y: i32,
}

5. std::clone::Clone

#[derive(Clone)]
struct Point {
    x: i32,
    y: i32,
}

6. std::ops::Add

use std::ops::Add;

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,
        }
    }
}

7. std::iter::Iterator

struct Counter {
    count: u32,
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;
        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}