1.4.1 更多特质

01-更多特质 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/bare-metal/aps/uart/traits.html

1.4.1 更多特质

我们推导出Debug特征。实现更多一些特征会很有用 也是。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
use core::fmt::{self, Write};

impl Write for Uart {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        for c in s.as_bytes() {
            self.write_byte(*c);
        }
        Ok(())
    }
}

// 安全:`Uart`仅包含一个指向设备内存的指针,可以是
// 从任何上下文访问。
unsafe impl Send for Uart {}
  • 实施Write让我们使用write!和writeln!宏与我们的 Uart类型。

  • Send是一个自动特征,但不会自动实现,因为它不是 为指针实现。

最后修改 August 11, 2026: 更新 (70a5af133)