gpt4 book ai didi

rust - 要求在继承特征的关联类型上绑定(bind)特征

转载 作者:行者123 更新时间:2023-11-29 07:43:53 24 4
gpt4 key购买 nike

我有一个特征 Foo 继承自另一个特征 BarBar 有一个关联类型 BazFoo 约束 Baz,这样 Baz 必须实现 Hoge

trait Hoge {}

trait Bar {
type Baz;
}

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

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

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

rustc 提示 EO277 除非我明确限制 T:

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

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

最佳答案

可悲的是(或不是),你必须重复边界。

去年我开了一个issue认为类型检查器不一致。代码与您的相似。

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

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:

  • 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.

今天我开了一个issue请求将此信息添加到文档中。

关于rust - 要求在继承特征的关联类型上绑定(bind)特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com