# 幻影类型

幻影类型（phantom type）是一种类型参数，它出现在类型的名称中，却不出现在该类型的运行时表示里，因此它不携带任何被存储的值，也没有任何运行时行为；它存在的唯一目的，是让编译器能够区分在其他方面完全相同的表示，并拒绝把二者混用的代码。<sup>[1](https://doc.rust-lang.org/nightly/rust-by-example/generics/phantom.html)</sup> 这一术语由当时在[乌得勒支大学](https://www.edgepedia.org/zh/utrecht-university)（Utrecht University）的计算机科学家达恩·莱延（Daan Leijen）与埃里克·梅耶尔（Erik Meijer）提出，用来指称那些不使用自身类型实参的参数化类型；他们用这一技术把领域特定语言以类型安全的方式嵌入 Haskell。<sup>[2](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)</sup><sup> • </sup><sup>[3](https://www.usenix.org/events/dsl99/full_papers/leijen/leijen.pdf)</sup>

| 要点 | 详情 |
|---|---|
| 定义 | 幻影类型参数不会出现在运行时，只在编译期接受静态检查，而且仅在编译期检查；它不占存储，也没有运行时行为。<sup>[1](https://doc.rust-lang.org/nightly/rust-by-example/generics/phantom.html)</sup> |
| 起源 | 该术语由莱延与梅耶尔提出，用于指称不使用自身类型实参的参数化类型，并应用于在 Haskell 中以类型安全方式嵌入领域特定语言。<sup>[2](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)</sup> |
| 典型示例 | `data Money currency = Money Double`，配合空标记类型 `EUR` 与 `USD`（没有任何构造子的类型），把不同货币区分开，使欧元与美元无法相加。<sup>[4](https://www.haskellmooc.cses.fi/part2)</sup> |
| Rust 中的编码 | `std::marker::PhantomData<T>` 是零大小标记：对任意 `T`，都有 `size_of::<PhantomData<T>>() == 0` 且 `align_of::<PhantomData<T>>() == 1`。<sup>[5](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)</sup> |
| Haskell 的角色 | GHC 为类型参数指定三种角色之一：名义（nominal）、表示（representational）或幻影（phantom）；数据类型与类型同义词的默认角色是幻影。<sup>[6](https://downloads.haskell.org/~ghc/9.4.1/docs/users_guide/exts/roles.html)</sup> |
| 典型用途 | 区分货币；区分米与英尺等物理单位；区分 `Connection<Disconnected>` 与 `Connection<Connected>` 等连接状态；以及外部函数接口的句柄。<sup>[7](https://www.hightechmind.io/rust/066-phantom-types.html)</sup><sup> • </sup><sup>[5](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)</sup> |
| 已知局限 | 经典幻影类型能在构造值时施加约束，但在解构值时，若不额外加标记并做运行时检查，就无法利用这些约束。<sup>[2](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)</sup> |

## 工作原理

幻影类型在类型检查器层面为类型附加一个标记，同时不触动其运行时表示。在 Haskell 中，标记类型声明时完全不带构造子，因此不存在任何属于它们的值；参数化类型则干脆忽略自己的参数。Haskell Mooc 的示例定义了 `data EUR`、`data USD` 与 `data Money currency = Money Double`，然后给出常量 `dollar :: Money USD` 和 `twoEuros :: Money EUR`。全部工作都由类型签名完成：若没有这些签名，Haskell 会推断出类似 `Double -> Money a -> Money b` 的类型，那就允许把任意货币加到任意另一种货币上。<sup>[4](https://www.haskellmooc.cses.fi/part2)</sup>

**Rust 的标记。** Rust 要求结构体的每个类型参数都被使用，因此未被使用的参数必须通过 `std::marker::PhantomData<T>` 来引用——这是一种零大小类型，它告诉编译器：该结构体表现得仿佛存有一个 `T`，尽管实际上并没有。<sup>[5](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)</sup> 《Rust by Example》教程展示了一个 `PhantomTuple<A, B>`，它持有一个 `A` 和一个 `PhantomData<B>`：系统为 `A` 分配存储，却不给 `B` 分配，因此 `B` 无法参与运算，但 `PhantomTuple<char, f32>` 与 `PhantomTuple<char, f64>` 仍是彼此不同的类型。<sup>[1](https://doc.rust-lang.org/nightly/rust-by-example/generics/phantom.html)</sup> 《Rustonomicon》把 `PhantomData` 描述为不占空间，却在静态分析的意义上模拟一个给定类型的字段，这会影响型变（variance）、自动 trait 与析构检查。<sup>[8](https://doc.rust-lang.org/nightly/nomicon/phantom-data.html)</sup>

Rust 的文档谨慎地区分了两个相关概念：幻影类型参数就是从未被使用的类型参数，而 `PhantomData` 是标准库提供的装置，用来满足编译器对占位使用的要求；`PhantomData` 本身与“幻影类型”相关，但并不等同。<sup>[5](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)</sup>

## 应用

**单位与货币。** 最常见的用途是防止混用共享同一表示的值。幻影类型可以区分米与英尺、欧元与美元、已规范化与未规范化的数据，于是期望某个标记的函数不会接受另一个标记的值。<sup>[7](https://www.hightechmind.io/rust/066-phantom-types.html)</sup> 在形式化验证中，同一思想构成了类型安全物理量的基础：在[国际量制](https://www.edgepedia.org/zh/international-system-of-quantities)（International System of Quantities）的 Isabelle/HOL 机械化实现中，量以量纲类型为参数，从而只有同一量纲的量才能相互等同。<sup>[9](https://arxiv.org/abs/2302.07629)</sup>

**状态机。** 把协议的各状态编码为幻影参数，可使非法状态转移变成类型错误：类型为 `Connection<Disconnected>` 的连接所提供的操作，与类型为 `Connection<Connected>` 的连接不同，类型系统会阻止使用一把已上锁的锁。<sup>[7](https://www.hightechmind.io/rust/066-phantom-types.html)</sup> Scala 关于擦除定义（erased definitions）的文档展示了同样的模式，只是改用证据参数：一个 `Machine[S]`，其 `turnedOn` 方法要求编译期证据 `IsOff[S]`，而该证据只对 `Off` 存在，因此连续两次调用 `turnedOn` 无法通过编译；这些证据实参在运行时从不被使用。<sup>[10](https://www.scala-lang.org/api/3.3_LTS/docs/docs/reference/experimental/erased-defs.html)</sup>

**外部接口与泛型编程。** 在 Rust 中，包装 `*mut ()` 类型不透明外部句柄的结构体，可以携带一个幻影参数，记录该句柄所指的 Rust 类型，于是类型检查器能够追踪运行时看不见的信息。<sup>[5](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)</sup> 在研究文献中，幻影类型支撑带类型的类型表示与带类型的[高阶抽象语法](https://www.edgepedia.org/zh/higher-order-abstract-syntax)树，进而支撑 Haskell 与 [Standard ML](https://www.edgepedia.org/zh/standard-ml) 等语言中的带类型泛型函数、动态类型与分阶段编译。<sup>[2](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)</sup>

## 理论与历史

莱延与梅耶尔于 1999 年在第二届 USENIX 领域特定语言会议（得克萨斯州奥斯汀）上，以 Haskell/DB 为背景提出了这一技术——Haskell/DB 是一个生成 SQL 的领域特定嵌入式编译器。<sup>[3](https://www.usenix.org/events/dsl99/full_papers/leijen/leijen.pdf)</sup> 康奈尔大学（Cornell University）的詹姆斯·切尼（James Cheney）与[波恩大学](https://www.edgepedia.org/zh/university-of-bonn)（University of Bonn）的拉尔夫·欣策（Ralf Hinze）后来在《一等幻影类型》（First-Class Phantom Types，康奈尔技术报告 TR2003-1901，2003 年 7 月 10 日发布）中扩展了这一思想。他们观察到，经典幻影类型虽然能保证只有良构数据才能被构造出来，但若不额外加标记并做运行时检查，就不允许类型安全的解构；他们的方案把这些约束显式表达为数据构造子上 `with` 子句中的类型方程，并为如此扩展的类 Haskell 语言证明了类型可靠性与可判定性。<sup>[2](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)</sup><sup> • </sup><sup>[11](https://ecommons.cornell.edu/entities/publication/850fddd8-da52-4ecb-8e01-d068b3488bdb)</sup>

Haskell 的角色系统形式化了参数对类型同一性的重要程度。若参数具有名义角色，两个不同的实参必须完全相同；若为表示角色，它们必须具有相同的表示；若为幻影角色，则无需更多信息，因此即便 `Age` 与 `Bool` 毫不相干，`Phant Age` 与 `Phant Bool` 也具有相同的表示。GHC 会自动推断角色，其中数据类型与类型同义词默认取幻影角色，类默认取名义角色。<sup>[6](https://downloads.haskell.org/~ghc/9.4.1/docs/users_guide/exts/roles.html)</sup>

## 相关技术与实际限制

**不透明类型与包装类型。** Scala 的不透明类型（opaque types）解决的是一个相邻的问题：以 `String` 为基础的 `Id` 与 `Password` 之类的类型别名无法防止值被混用，因为别名会被替换为其底层类型；而 case 类包装器则会带来内存分配开销。不透明类型仅在其定义作用域内透明，在运行时总会被擦除，且从不装箱或拆箱；SIP-35 提案演示了一种 `Tagged[S, T]` 编码，其中 `S` 被一个仅在编译期使用的任意 `T` 标记，并明确指出其中一个参数就是幻影类型。<sup>[12](https://docs.scala-lang.org/sips/opaque-types.html)</sup>

**运行时检查的变体。** Python 的 `phantom-types` 库走的是另一条路：它把基类与谓词函数结合起来，使值依据某个界限接受校验。其文档警告了两种失效模式：若幻影类型未正确指明其界限，静态类型检查器在进行类型守卫时可能无意中擦除运行时类型；此外，幻影类型与可变数据不兼容，绝不应被用来收窄可变类型。<sup>[13](https://phantom-types.readthedocs.io/en/main/pages/composing-types.html)</sup>

**精化类型。** 幻影类型用彼此不同的类型给值打上标记，但无法表达对值本身的约束。精化类型（refinement types）解决的是另一个问题：它用逻辑谓词来充实类型系统，这些谓词界定了某个类型所描述的值集合，从而让开发者可以指定检查器应当验证哪些不变式。<sup>[14](https://arxiv.org/abs/2010.07763)</sup>

## References

1. [Phantom type parameters, Rust By Example](https://doc.rust-lang.org/nightly/rust-by-example/generics/phantom.html)
2. [James Cheney and Ralf Hinze, First-Class Phantom Types](https://www.researchgate.net/publication/213885544_First-Class_Phantom_Types)
3. [Daan Leijen and Erik Meijer, Domain Specific Embedded Compilers, DSL'99](https://www.usenix.org/events/dsl99/full_papers/leijen/leijen.pdf)
4. [Haskell Mooc, part 2: Phantom Types](https://www.haskellmooc.cses.fi/part2)
5. [std::marker::PhantomData, Rust standard library documentation](https://doc.rust-lang.org/core/marker/struct.PhantomData.html)
6. [Roles, Glasgow Haskell Compiler 9.4.1 User's Guide](https://downloads.haskell.org/~ghc/9.4.1/docs/users_guide/exts/roles.html)
7. [Phantom Types (Type-Safe Units), Functional Rust](https://www.hightechmind.io/rust/066-phantom-types.html)
8. [PhantomData, The Rustonomicon](https://doc.rust-lang.org/nightly/nomicon/phantom-data.html)
9. [Simon Foster and Burkhart Wolff, Automated Reasoning for Physical Quantities, Units, and Measurements in Isabelle/HOL](https://arxiv.org/abs/2302.07629)
10. [Erased Definitions, Scala 3 documentation](https://www.scala-lang.org/api/3.3_LTS/docs/docs/reference/experimental/erased-defs.html)
11. [First-Class Phantom Types, Cornell eCommons (TR2003-1901)](https://ecommons.cornell.edu/entities/publication/850fddd8-da52-4ecb-8e01-d068b3488bdb)
12. [SIP-35: Opaque types, Scala Documentation](https://docs.scala-lang.org/sips/opaque-types.html)
13. [Composing types, phantom-types documentation](https://phantom-types.readthedocs.io/en/main/pages/composing-types.html)
14. [Refinement Types: A Tutorial](https://arxiv.org/abs/2010.07763)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts › Advanced and dependent type features

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/phantom-type

English original: https://www.edgepedia.org/phantom-type
