I have an enum that has different variant possibilities like so:
pub enum Enum {
Empty,
Single(Struct),
Multi(Vec<Struct>),
}
And I want to create the typical three iteration functions to get Structs for Enum: one .iter() for an iterator of references, and two flavors of .into_iter() to get iterators over references and over values. How does one do this?
Here is my failed attempt:
use std::{iter, slice, vec};
#[derive(Debug)]
pub struct Struct(u32);
#[derive(Debug)]
pub enum Enum {
Empty,
Single(Struct),
Multi(Vec<Struct>),
}
impl Enum {
fn iter(&self) -> slice::Iter<'_, Struct> {
match self {
Enum::Empty => iter::empty(),
Enum::Single(s) => iter::once(s),
Enum::Multi(v) => v.iter(),
}
}
}
impl IntoIterator for Enum {
type Item = Struct;
type IntoIter = vec::IntoIter<Struct>;
fn into_iter(self) -> Self::IntoIter {
match self {
Enum::Empty => iter::empty(),
Enum::Single(s) => iter::once(s),
Enum::Multi(v) => v.into_iter(),
}
}
}
impl<'a> IntoIterator for &'a Enum {
type Item = &'a Struct;
type IntoIter = slice::Iter<'a, Struct>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
fn main() {
let enums = vec![
Enum::Empty,
Enum::Single(Struct(1)),
Enum::Multi(vec![Struct(2), Struct(3)])];
for e in enums {
for s in e.iter() {
println!(".iter() over refs: {:?}", s);
}
for s in &e { // leverages IntoIterator for &'a Enum
println!(".into_iter() over refs: {:?}", s);
}
for s in e { // leverages IntoIterator for Enum
println!(".into_iter() moves: {:?}", s);
}
}
}
I'm failing to see how to coerce the iter::empty and iter::once into the slice::Iter and vec::IntoIter, or is that even the right thing to want to do?