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

标签 rust

我有一个特征 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/

相关文章:

algorithm - 如何通过有损近似的计算点确定贝塞尔曲线控制点?

reference - 为什么要使用对 i32 的不可变引用

rust - 为什么这个特性不是对象安全的?

multithreading - Rust mpsc::Sender 不能在线程间共享?

rust - 为什么 `get` 对 std::vec::Vec 和 &std::vec::Vec 都有效?

rust - 如何使用分隔符将 HashSet 的元素连接到字符串中

rust - 为什么 Rust 中的循环如此缓慢?

module - 看不懂 Rust 模块系统

rust - 编写一个函数来获取引用和值类型的迭代

string - 如何将整数转换为字符串?