知识卡片

普通读书笔记卡 · 743.d.2.b.1.a

新类型区分相同底层表示

理解等级:中级

单字段结构体可为同一种底层值建立不同语义身份,例如磅力秒与牛顿秒都用f64表示,却不能直接互传。别名仅作命名提示,newtype则让编译器检查混用。转换必须明确执行单位换算,不能只拆开再原样包装;表示兼容需求还应核对repr(transparent)规则。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Item 6: Embrace the newtype pattern · 查看原书依据

      PoundForceSeconds = f64; /// Fire the thrusters. Returns generated impulse. pub fn thruster_impulse(direction: Direction) -> PoundForceSeconds { // ... return 42.0; } /// Units for force. pub type NewtonSeconds = f64; /// Update trajectory model for impulse. pub fn update_trajectory(force: NewtonSeconds) { // ... } However, the type aliases are effectively j

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Item 6: Embrace the newtype pattern》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u035-ch01-045)。 - 结论依据:原文在“PoundForceSeconds”附近的定义、例子或代码支撑本卡核心说明:单字段结构体可为同一种底层值建立不同语义身份,例如磅力秒与牛顿秒都用f64表示,却不能直接互传。边界按已读前提解释;示例未执行。 - 原始内容:PoundForceSeconds = f64; /// Fire the thrusters. Returns generated impulse. pub fn thruster_impulse(direction: Direction) -> PoundForceSeconds { // ... return 42.0; } /// Units for force. pub type NewtonSeconds = f64; /// Update trajectory model for impulse. pub fn update_trajectory(force: NewtonSeconds) { // ... } However, the type aliases are effectively j