gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:36:17 25 4
gpt4 key购买 nike

我有一个特征,我想要求实现类型可以通过借用进行迭代。我设法使用 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/

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