Hi, I'm learning about iterators and thought I'd test myself with a trivial example, but I'm having problems.
The challenge I set myself was to write 3 iterators (consuming, immutable reference and mutable reference) for this simple struct:
#[derive(Debug)]
struct FullName {
first: String,
middle: String,
last: String,
}
Here's the 'consuming' iterator, which seems to work OK:
struct IntoIter {
name: FullName,
i: u8,
}
impl Iterator for IntoIter {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
self.i += 1;
match self.i {
1 => Some(self.name.first.clone()),
2 => Some(self.name.middle.clone()),
3 => Some(self.name.last.clone()),
_ => None,
}
}
}
impl IntoIterator for FullName {
type Item = String;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter { name: self, i: 0 }
}
}
And here's the immutable reference iterator, which also seems to be OK:
struct Iter<'a> {
name: &'a FullName,
i: u8,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.i += 1;
match self.i {
1 => Some(&self.name.first),
2 => Some(&self.name.middle),
3 => Some(&self.name.last),
_ => None,
}
}
}
impl<'a> IntoIterator for &'a FullName {
type Item = &'a str;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
Iter { name: self, i: 0 }
}
}
But I can't figure out how to do the mutable reference iterator. I've tried letting the compiler guide me, but I can't get the code to compile, let alone work correctly. This is as far as I get:
struct IterMut<'a> {
name: &'a mut FullName,
i: u8,
}
impl <'a> Iterator for IterMut<'a> {
type Item = &'a mut String;
// does NOT compile
fn next(&mut self) -> Option<Self::Item> {
self.i += 1;
match self.i {
1 => Some(&mut self.name.first),
2 => Some(&mut self.name.middle),
3 => Some(&mut self.name.last),
_ => None,
}
}
}
impl <'a> IntoIterator for &'a mut FullName {
type Item = &'a mut String;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> Self::IntoIter {
IterMut { name: self, i: 0 }
}
}
How can I fix this?