要求在继承特征的关联类型上绑定特征 [英] Requiring a trait bound on the associated type of an inherited trait

查看:67
本文介绍了要求在继承特征的关联类型上绑定特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特征 Foo 继承自另一个特征 Bar.Bar 有一个关联类型 Baz.Foo 约束 Baz 使得 Baz 必须实现 Hoge.

I have a trait Foo inheriting from another trait Bar. Bar has an associated type Baz. Foo constrains Baz such that Baz must implement Hoge.

trait Hoge {}

trait Bar {
    type Baz;
}

trait Foo: Bar where Self::Baz: Hoge {}

然而,当我定义一个需要泛型类型 T 来实现 Foo 的泛型函​​数时,

However, when I define a generic function requiring the generic type T to implement Foo,

// [DESIRED CODE]
fn fizz<T: Foo>(buzz: T) {
    // ...
}

rustc 抱怨 EO277 除非我明确限制 T:

rustc complains with EO277 unless I constrain T explicitly:

fn fizz<T: Foo>(buzz: T) where T::Baz: Hoge {
    // ...
}

我不明白为什么我需要这样做.我希望能够编写[DESIRED CODE].推荐的方法是什么?

I do not understand why I need to do this. I would like to be able to write [DESIRED CODE]. What is the recommended way to do this?

推荐答案

遗憾的是(或不是),您必须重复这些界限.

Sadly (or not), you have to repeat the bounds.

去年我打开了一个问题,认为类型检查器不一致.代码与您的相似.

Last year I opened a issue thinking that the type checker was being inconsistent. The code is similar to yours.

@arielb1 关闭了问题并说这是预期的行为并给出了以下解释:

@arielb1 closed the issue and said that this was the intended behavior and gave this explanation:

问题是我们不希望隐含的边界太多可用于函数,因为这会导致远距离的脆弱性导致函数停止编译的更改.基本上有3个函数可用的边界种类:

The thing is that we don't want too many bounds to be implicitly available for functions, as this can lead to fragility with distant changes causing functions to stop compiling. There are basically 3 kinds of bounds available to a function:

  • 来自显式 where 子句的界限 - 例如T: B 当你有那个子句时.这包括半显式"Sized 界限.
  • 来自显式 where-clauses 的超特征的边界 - where-clause 为其超特征添加边界(如 trait B: AT: B 边界添加了一个T:A 绑定).
  • 参数生命周期属性的边界(outlives/implicator/implied bounds).这些只是一生的界限,并且与当前问题无关.rust-lang/rfcs#1214 涉及他们很多.
  • bounds from explicit where-clauses - e.g. T: B when you have that clause. This includes the "semi-explicit" Sized bound.
  • bounds from supertraits of explicit where-clauses - a where-clause adds bounds for its supertraits (as trait B: A, the T: B bound adds a T: A bound).
  • bounds from the lifetime properties of arguments (outlives/implicator/implied bounds). These are only lifetime bounds, and irrelevant for the current problem. rust-lang/rfcs#1214 involved them a great deal.

如果您的绑定不在列表中,则必须明确添加它,如果你想使用它.我想这应该是一个常见问题条目.

If your bound isn't in the list, you will have to add it explicitly if you want to use it. I guess this should be a FAQ entry.

今天我打开了一个问题 请求将此信息添加到文档.

Today I opened an issue to request that this information to be added to the docs.

这篇关于要求在继承特征的关联类型上绑定特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆