本文介绍了为什么使用我的类型作为外部类型合法的参数来实现外部特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改一些代码以依赖于 rand 0.5 版.起初,我担心如何使用 Standard 生成我自己类型的随机值,但我发现这是合法的:

I am modifying some code to depend on rand version 0.5. At first, I was worried how I would enable generating random values of my own types with Standard, but I found out this is legal:

impl ::rand::distributions::Distribution<MyType> for ::rand::distributions::Standard {
    // ...
}

为什么是合法的?我认为为外部类型实现外部特征是 非法.

Why is it legal? I thought implementing an external trait for an external type is illegal.

推荐答案

这些规则(称为孤立规则一致性规则)的全部目的是避免给定特征/类型组合的任何冲突实现.从 Rust 1.0 开始,人们认为,对于允许谁为类型实现 trait 的随意",这不符合追求稳固稳定性的语言.

The entire purpose of these rules (called the orphan rules or coherence rules) is to avoid having any conflicting implementations for a given trait/type combination. Since Rust 1.0, it is believed that it would not be in line with a language striving for solid stability to be "willy-nilly" about who is allowed to implement a trait for a type.

这种特殊实现类型的一个非常常见的例子是From:

A very common example of this particular type of implementation is From:

impl From<MyType> for i32 {
    // ...
}

通过使用本地类型参数化 trait,对于谁在实现 trait 仍然没有歧义.一种思考方式是将 Distribution 视为不是 trait 而是 trait 构造函数 .Distribution 的每个实例都会创建一个新特征,这是为案例定制的.

By parameterizing the trait with a local type, there's still no ambiguity about who is implementing the trait. One way of thinking about it would be treating Distribution as not a trait but a trait constructor . Each instance of Distribution creates a new trait, one that's custom-made for the case.

另见:

— 这不是真的,但这是一个合理的类比.

— This isn't true, but it's a reasonable analogy.

这篇关于为什么使用我的类型作为外部类型合法的参数来实现外部特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:06