How to Bypass Rust's Orphan Rule

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

How to Bypass Rust’s Orphan Rule

How to Bypass Rust’s Orphan Rule

Contents What Is the Orphan Rule Actually Protecting Against?Why the Two Usual Workarounds Fall Short 1. Building it into the library2. Wrap it in a NewType yourselfAdding a Generic Slot to the TraitThe Position of the Local Type MattersA Truly Standalone models CrateReal-World Example: How This Works in KovaWrite Rust for long enough, and you are bound to run into error[E0117].

如何绕过 Rust 的孤儿规则

目录:孤儿规则到底在防范什么?为什么两种常见的变通方法不够好?1. 将其构建到库中;2. 自己将其包装在 NewType 中;为 Trait 添加泛型槽;本地类型的位置很重要;一个真正独立的 models crate;真实案例:这在 Kova 中是如何工作的。只要你写 Rust 的时间够长,就一定会遇到 error[E0117]。

Take a simple, everyday scenario. You pull in a serialization library that defines a ToJson trait, along with a third-party type library like uuid. You want to turn a uuid::Uuid into JSON, so you naturally write:impl ToJson for uuid::Uuid { fn to_json(&self) -> String { format!(""{}"", self) } }And the compiler immediately stops you:error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate

以一个简单的日常场景为例。你引入了一个定义了 ToJson trait 的序列化库,以及像 uuid 这样的第三方类型库。你想将 uuid::Uuid 转换为 JSON,于是你自然地写道:impl ToJson for uuid::Uuid { fn to_json(&self) -> String { format!(""{}"", self) } } 编译器会立即阻止你:error[E0117]: 只有在当前 crate 中定义的 trait 才能为在 crate 外部定义的类型实现。

This is Rust’s well-known Orphan Rule. Once people hit this wall, they usually either complain that the compiler is too rigid or dutifully wrap the type in a NewType. But if you look closely at how the Orphan Rule actually works, it is not a dead end. By design, it leaves a pretty wide door open.

这就是 Rust 众所周知的孤儿规则。一旦人们撞上这堵墙,通常要么抱怨编译器太死板,要么乖乖地将类型包装在 NewType 中。但如果你仔细观察孤儿规则的实际运作方式,就会发现它并非死胡同。从设计上讲,它留了一扇相当宽敞的门。

What Is the Orphan Rule Actually Protecting Against?Setting the jargon aside, the logic behind the Orphan Rule is simple: if you want a type to implement a trait, at least one of those two things (the type or the trait) must belong to your own crate. In plain English, you don’t get to make rules for someone else’s types.

孤儿规则到底在防范什么?抛开术语不谈,孤儿规则背后的逻辑很简单:如果你想让一个类型实现一个 trait,那么这两者(类型或 trait)中至少有一个必须属于你自己的 crate。用通俗的话说,你不能为别人的类型制定规则。

Suppose crate A implements ToJson for uuid::Uuid and outputs a hyphenated UUID string, while crate B also implements ToJson for uuid::Uuid and outputs 32 raw hex characters without hyphens. If a project depends on both A and B, the compiler has a problem when it sees uuid.to_json(): which implementation should it pick?

假设 crate A 为 uuid::Uuid 实现了 ToJson 并输出带连字符的 UUID 字符串,而 crate B 也为 uuid::Uuid 实现了 ToJson 并输出 32 个不带连字符的原始十六进制字符。如果一个项目同时依赖 A 和 B,当编译器看到 uuid.to_json() 时就会遇到问题:它应该选择哪种实现?

To prevent this kind of global conflict, Rust enforces coherence, and the Orphan Rule is how it gets enforced. There is nothing wrong with the rule itself. It keeps the Rust ecosystem from turning into a mess as dependency trees grow. The catch is that real-world projects constantly run into a very common need: making a third-party type implement a trait from another third-party crate. Neither the type nor the trait is yours, yet gluing libraries together like this happens all the time. So what can you do?

为了防止这种全局冲突,Rust 强制执行一致性,而孤儿规则就是执行这一原则的方式。规则本身没有错。它防止了 Rust 生态系统随着依赖树的增长而变得混乱。问题在于,现实世界的项目经常遇到一个非常普遍的需求:让第三方类型实现另一个第三方 crate 中的 trait。类型和 trait 都不属于你,但像这样将库粘合在一起的情况却时有发生。那么你能做什么呢?

Why the Two Usual Workarounds Fall ShortRight now, the Rust ecosystem mostly relies on two workarounds. Both appear to solve the problem on the surface, but because neither addresses the root cause, they get awkward fast.

为什么两种常见的变通方法不够好?目前,Rust 生态系统主要依赖两种变通方法。两者表面上似乎都解决了问题,但由于都没有解决根本原因,它们很快就会变得笨拙。

  1. Building it into the libraryMany foundational crates take this route: since users can’t write the impl themselves, the crate provides it internally. Because ToJson is defined inside the crate, implementing it for any external type satisfies the Orphan Rule. Open up the Cargo.toml of one of these crates, and you will see a long list of feature flags: with-uuid, with-chrono, with-time, with-jiff, with-url, with-rust-decimal, and so on.

  2. 将其构建到库中。许多基础 crate 采取这种路线:由于用户无法自己编写 impl,crate 会在内部提供它。因为 ToJson 是在 crate 内部定义的,所以为任何外部类型实现它都满足孤儿规则。打开其中一个 crate 的 Cargo.toml,你会看到一长串功能标志:with-uuid, with-chrono, with-time, with-jiff, with-url, with-rust-decimal 等等。

It looks helpful at first, but it tries to enumerate an open, constantly changing ecosystem inside a single crate. That approach has clear limits, and the downsides show up quickly:You can never support everything. Today the community favors chrono, tomorrow people switch to jiff, and next week your team builds its own internal Money type. If the library doesn’t have built-in support, you are stuck waiting for a release or opening a PR yourself.

起初这看起来很有帮助,但它试图在一个单一的 crate 中枚举一个开放且不断变化的生态系统。这种方法有明显的局限性,缺点很快就会显现出来:你永远无法支持所有东西。今天社区偏爱 chrono,明天人们转向 jiff,下周你的团队又构建了自己的内部 Money 类型。如果库没有内置支持,你就只能等着发布或者自己提交 PR。

Version lock-in. When a third-party type crate bumps its major version, your whole dependency tree gets stuck until the trait crate publishes a matching update.Hardcoded behavior. Maybe the library serializes DateTime as an ISO-8601 string by default, while your API spec requires an integer timestamp in milliseconds. Because the implementation lives inside the library, you have no way to change it.

版本锁定。当第三方类型 crate 升级其主版本时,你的整个依赖树都会被卡住,直到 trait crate 发布相应的更新。硬编码行为。也许库默认将 DateTime 序列化为 ISO-8601 字符串,而你的 API 规范要求以毫秒为单位的整数时间戳。因为实现位于库内部,你无法更改它。

  1. Wrap it in a NewType yourselfWhen the library doesn’t have built-in support, or its default behavior doesn’t fit your needs, you fall back to the familiar NewType pattern:pub struct MyUuid(pub uuid::Uuid); impl ToJson for MyUuid { fn to_json(&self) -> String { format!(""{}"", self.0) } }

  2. 自己将其包装在 NewType 中。当库没有内置支持,或者其默认行为不符合你的需求时,你会退回到熟悉的 NewType 模式:pub struct MyUuid(pub uuid::Uuid); impl ToJson for MyUuid { fn to_json(&self) -> String { format!(""{}"", self.0) } }

Wrapping one or two types is fine. The trouble starts when a moderately complex domain model mixes Uuid, Url, DateTime, HashMap, and custom domain types all at once. Once you wrap everything into MyUuid, MyUrl, and MyDateTime, your business logic gets littered with .0, and you spend your time constantly wrapping and unwrapping values. It gets old very quickly.

包装一两个类型还可以。当一个中等复杂的领域模型同时混合了 Uuid、Url、DateTime、HashMap 和自定义领域类型时,麻烦就开始了。一旦你把所有东西都包装成 MyUuid、MyUrl 和 MyDateTime,你的业务逻辑就会充斥着 .0,你将花费大量时间不断地包装和解包值。这很快就会让人厌烦。

NewType is a genuinely useful pattern in Rust for expressing domain meaning, hiding internals, or enforcing invariants. The problem is that when you only use it to appease the Orphan Rule on types that didn’t need a wrapper in the first place, your code bloats quickly.So is there a way to let users decide how third-party types implement a trait, without wrapping everything in NewTypes?

NewType 是 Rust 中一种真正有用的模式,用于表达领域含义、隐藏内部细节或强制执行不变量。问题在于,当你仅仅为了满足孤儿规则而对那些本来不需要包装器的类型使用它时,你的代码会迅速膨胀。那么,有没有一种方法可以让用户决定第三方类型如何实现 trait,而无需将所有东西都包装在 NewType 中呢?

Adding a Generic Slot to the TraitLet’s go back to the rule: either the type or the trait must belong to the current crate.Many developers assume the compiler only looks at Trait and Type in impl Trait for Type. In fact, under Rust’s Orphan Rule (RFC 2451), the trait’s own generic type parameters are also part of the check.

为 Trait 添加泛型槽。让我们回到规则:类型或 trait 必须属于当前 crate。许多开发者认为编译器在 impl Trait for Type 中只查看 Trait 和 Type。事实上,根据 Rust 的孤儿规则(RFC 2451),trait 自身的泛型类型参数也是检查的一部分。

Put simply, in impl Trait

for Type, as long as a local type appears in the trait’s generic parameters, and there are no uncovered type parameters before it, the compiler knows this implementation belongs exclusively to the current crate. No other crate can conflict with it, so the compiler lets it through.

简单来说,在 impl Trait

for Type 中,只要本地类型出现在 trait 的泛型参数中,并且其前面没有未覆盖的类型参数,编译器就知道此实现专门属于当前 crate。没有其他 crate 可以与之冲突,因此编译器会允许它通过。

Take this example:impl ToJson for uuid::Uuid { // … }ToJson is a foreign trait, and Uuid is a foreign type, but MyApp is defined in the current crate. Because it sits in the trait’s generic parameter position, this impl satisfies the Orphan Rule.Following this idea, a library author only needs to take one extra step when designing a trait: leave a generic parameter on the trait as an extension point for users.For example:pub trait ToJson<Ctx = ()> { fn to_json(&self) -> String; }

以这个例子为例:impl ToJson for uuid::Uuid { // … } ToJson 是外部 trait,Uuid 是外部类型,但 MyApp 是在当前 crate 中定义的。因为它位于 trait 的泛型参数位置,所以这个 impl 满足孤儿规则。遵循这个思路,库作者在设计 trait 时只需要多走一步:在 trait 上留下一个泛型参数作为用户的扩展点。例如:pub trait ToJson<Ctx = ()> { fn to_json(&self) -> String; }