实现 IntoIterator 的无约束类型参数
Unconstrained type parameter implementing IntoIterator
如何使用泛型类型参数实现 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)
}
}
这是我期望实现的行为。
fn main() {
let mut counter = Counter { top: 3 };
assert_eq!(
counter.into_iter().collect::<Vec<Id>>(),
vec![Id(0), Id(1), Id(2)]
);
}
无需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)
}
}
如何使用泛型类型参数实现 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)
}
}
这是我期望实现的行为。
fn main() {
let mut counter = Counter { top: 3 };
assert_eq!(
counter.into_iter().collect::<Vec<Id>>(),
vec![Id(0), Id(1), Id(2)]
);
}
无需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)
}
}