rust - 如何为 `IntoIter` 绑定(bind) `<&Self as IntoIterator>` 类型?

标签 rust traits lifetime

我有一个特征,我想要求实现类型可以通过借用进行迭代。我设法使用 for<'x> 做到了这一点。 &'x Self 上排名较高的特征界限 (HRTB) .

但是,我也想要求 IntoIter关联类型实现 ExactSizeIterator ,但我试图在类型系统中描述这一点的每一种方式都会导致编译问题,这些问题似乎源于 HRTB 的使用(我不完全相信我是否正确使用)。

这是(简化的)代码:


struct Thing<'thing>(&'thing ());

trait Trait<'thing>
    where
        for<'x> &'x Self: IntoIterator<Item = &'x Thing<'thing>>,
        // Compiles fine until uncommenting this line:
        //for<'x> <&'x Self as IntoIterator>::IntoIter: ExactSizeIterator
{ }

struct Bucket<'things> {
    things: Vec<Thing<'things>>,
}

struct BucketRef<'a, 'things: 'a> {
    bucket: &'a Bucket<'things>,
}

impl<'x, 'a, 'things: 'a> IntoIterator for &'x BucketRef<'a, 'things> {
    type Item = &'x Thing<'things>;
    type IntoIter = std::slice::Iter<'x, Thing<'things>>;
    fn into_iter(self) -> Self::IntoIter {
        self.bucket.things.iter()
    }
}

impl<'a, 'things: 'a> Trait<'things> for BucketRef<'a, 'things> { }

fn foo<'a, 'things>(anchor: &BucketRef<'a, 'things>) {
    println!("{}", ExactSizeIterator::len(&anchor.into_iter()));
}

正如所写的那样编译很好,但是当我尝试进一步限制 Trait 的边界时通过注释行,我收到以下编译器错误:
error[E0277]: the trait bound `for<'x> <&'x anchor::BucketRef<'a, 'things> as std::iter::IntoIterator>::IntoIter: std::iter::ExactSizeIterator` is not satisfied

在我的非编译器作者看来,给定 rustc似乎能够确定内部函数foo &BucketRef 的所有实例是 ExactSizeIterator s,它应该能够对 trait bound 做类似的事情,但这在现实中并没有得到证实。

任何人都可以向我解释为什么这不起作用,以及是否有更好的方法来表达边界本身或边界背后的意图?
active toolchain
----------------
stable-x86_64-unknown-linux-gnu (default)
rustc 1.43.0 (4fb7144ed 2020-04-20)

最佳答案

关于rust - 如何为 `IntoIter` 绑定(bind) `<&Self as IntoIterator>` 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727140/

相关文章:

rust - 如何使用本地未发布的箱子?

rust - 如何将两个同名的 header 附加到 Warp `Reply` ?

struct - Rust 结构无法替换 HashMap 中的特征

c++ - 对象如何成为子对象?

opengl - 在 Rust 中,你如何明确地将两个对象的生命周期联系在一起,而不相互引用?

rust - 什么特征阻止参数包含指向堆分配的数据的指针?

rust - HashMap Entry API 的生命周期/借用问题

PHP 特征公开方法和接口(interface)

module - 在单独的文件中定义特征

rust - 在测试函数上声明生命周期