我有一个特征,对于这个特征,我想要求实现类型可以通过借入来迭代。我已经成功地在&'x Self上使用了for<'x>更高级别的特征界限(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,它应该能够对特征界限执行类似的操作,但这在现实中并没有得到证实。
谁能给我解释一下为什么这不起作用,是否有更好的方式来表达约束本身或约束背后的意图?
active toolchain
----------------
stable-x86_64-unknown-linux-gnu (default)
rustc 1.43.0 (4fb7144ed 2020-04-20)发布于 2021-08-06 08:36:53
https://stackoverflow.com/questions/61727140
复制相似问题