Merge pull request #750 from Orefa/main

调整实现trait限制的翻译
pull/751/head
KaiserY 10 months ago committed by GitHub
commit 00af6f78d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -52,7 +52,7 @@ trait 体中可以有多个方法:一行一个方法签名且都以分号结
这会打印出 `1 new tweet: horse_ebooks: of course, as you probably already know, people`
其他依赖 `aggregator` crate 的 crate 也可以将 `Summary` 引入作用域以便为其自己的类型实现该 trait。实现 trait 时需要注意的一个限制是,只有当至少一个 trait 或者要实现 trait 的类型位于 crate 的本地作用域时,才能为该类型实现 trait。例如可以为 `aggregator` crate 的自定义类型 `Tweet` 实现如标准库中的 `Display` trait这是因为 `Tweet` 类型位于 `aggregator` crate 本地的作用域中。类似地,也可以在 `aggregator` crate 中为 `Vec<T>` 实现 `Summary`,这是因为 `Summary` trait 位于 `aggregator` crate 本地作用域中。
其他依赖 `aggregator` crate 的 crate 也可以将 `Summary` 引入作用域以便为其自己的类型实现该 trait。需要注意的限制是,只有在 trait 或类型至少有一个属于当前 crate 时,我们才能对类型实现该 trait。例如可以为 `aggregator` crate 的自定义类型 `Tweet` 实现如标准库中的 `Display` trait这是因为 `Tweet` 类型位于 `aggregator` crate 本地的作用域中。类似地,也可以在 `aggregator` crate 中为 `Vec<T>` 实现 `Summary`,这是因为 `Summary` trait 位于 `aggregator` crate 本地作用域中。
但是不能为外部类型实现外部 trait。例如不能在 `aggregator` crate 中为 `Vec<T>` 实现 `Display` trait。这是因为 `Display``Vec<T>` 都定义于标准库中,它们并不位于 `aggregator` crate 本地作用域中。这个限制是被称为 **相干性***coherence*)的程序属性的一部分,或者更具体的说是 **孤儿规则***orphan rule*),其得名于不存在父类型。这条规则确保了其他人编写的代码不会破坏你代码,反之亦然。没有这条规则的话,两个 crate 可以分别对相同类型实现相同的 trait而 Rust 将无从得知应该使用哪一个实现。

Loading…
Cancel
Save