[英]Unconstrained type parameter implementing IntoIterator
How do I implement IntoIterator with a generic type parameter without getting into this kind of error, I think is the same error than here but the solution proposed there is not valid in this context, also doing a method called iter
on Counter
would solve the issue but it won't be idiomatic我如何使用泛型类型参数实现 IntoIterator 而不会出现这种错误,我认为与此处的错误相同,但提出的解决方案在此上下文中无效,同时在Counter
上执行一个名为iter
的方法可以解决问题但它不会是惯用的
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Id(u32);
struct Counter {
top: u32
}
struct Iter<R: Iterator<Item = Id>>(R);
impl<R> Iterator for Iter<R>
where
R: Iterator<Item = Id>
{
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
// Unconstrained type parameter `I`
impl<I> IntoIterator for Counter
where
I: Iterator<Item = Id>
{
type Item = Id;
type IntoIter = I;
fn into_iter(self) -> Self::IntoIter {
Iter(0..self.top)
}
}
This is the behaviour I expect from the implementation.这是我期望从实现中得到的行为。
fn main() {
let mut counter = Counter { top: 3 };
assert_eq!(
counter.into_iter().collect::<Vec<Id>>(),
vec![Id(0), Id(1), Id(2)]
);
}
This can be solved without needing the I
type parameter:这可以在不需要I
类型参数的情况下解决:
struct Iter<R: Iterator<Item = u32>>(R);
impl<R> Iterator for Iter<R>
where
R: Iterator<Item = u32>,
{
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(Id)
}
}
impl IntoIterator for Counter {
type Item = Id;
type IntoIter = Iter<std::ops::Range<u32>>;
fn into_iter(self) -> Self::IntoIter {
Iter(0..self.top)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.