【问题标题】:type annotations required in the context of associated types an iterators关联类型和迭代器上下文中所需的类型注释
【发布时间】:2015-08-04 13:05:04
【问题描述】:

我创建了一个最小示例来说明我无法解决的类型推断问题。

trait A<'a> {
    type Item: Copy;
    type Iter: Iterator<Item=Self::Item>;

    fn items(&'a self) -> Self::Iter;

    fn consume(&'a self, i: Self::Item) -> Self::Item;

    fn f(&'a self) {
        let _ = self.items().map(|i| self.consume(i) as Self::Item);
    }
}

编译错误是

x.rs:10:30: 10:68 error: type annotations required: cannot resolve `<<Self as A<'_>>::Iter as core::iter::Iterator>::Item == _` [E0284]
x.rs:10         let _ = self.items().map(|i| self.consume(i) as Self::Item);

我查看了有关需要类型注释的其他问题,但这似乎是涉及关联类型的特殊情况。

【问题讨论】:

  • 在您的真实案例中需要'a 吗?删除它并允许生命周期推断可以编译代码。
  • 是的,我需要一生。我的代码在没有生命周期的情况下工作,但我必须添加它,然后代码停止编译,因为我问了这个问题。感谢您的帮助。

标签: rust


【解决方案1】:

我认为这是#24338,是由于编译器对特征的生命周期和相关类型感到困惑。可以通过将 f 方法的主体移动到单独的函数中来解决它(嵌套算作单独的,因为它们是独立进行类型检查的):

trait A<'a> {
    // ...

    fn f(&'a self) {
        f_body(self);

        fn f_body<'a, T: ?Sized + A<'a>>(x: &'a T) {
            let _ = x.items().map(|i| x.consume(i) as T::Item);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多