Requiring a trait bound on the associated type of an inherited trait
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 {}
However, when I define a generic function requiring the generic type T
to implement Foo
,
// [DESIRED CODE]
fn fizz<T: Foo>(buzz: T) {
// ...
}
rustc
complains with EO277
unless I constrain T
explicitly:
fn fizz<T: Foo>(buzz: T) where T::Baz: Hoge {
// ...
}
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 closed the issue and said that this was the intended behavior and gave this explanation:
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:
T: B
when you have that clause. This includes the "semi-explicit" Sized
bound. trait B: A
, the T: B
bound adds a T: A
bound). 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.
链接地址: http://www.djcxy.com/p/92108.html上一篇: Java中虚假的唤醒事件是否真的发生?
下一篇: 要求在相关类型的继承特征上绑定特征