Hi y'all,
I want to implement IntoIterator
for a struct Rgb666(u8, u8, u8)
, so that it basically returns those 3 u8
's in an iterator form.
How can I do it? I attempted this and failed because it requires Generic Associated Types which are unstable:
impl<'a> IntoIterator for Rgb666 {
type Item = u8;
type IntoIter<'a> = Iter<'a, Self::Item>;
fn into_iter(self) -> Self::IntoIter {
[self.0, self.1, self.2].into_iter()
}
}
What else can I do to achieve that?
pub struct IntoIter(std::array::IntoIter<u8, 3>);
impl Iterator for IntoIter {
type Item = u8;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Rgb666(u8, u8, u8);
impl IntoIterator for Rgb666 {
type Item = u8;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
let Self(r, g, b) = self;
IntoIter(std::array::IntoIter::new([r, g, b]))
// or `IntoIter([r, g, b].into_iter())` in edition 2021
}
}
The point of IntoIterator
is that creating the iterator consumes self
(hence "into"), so your IntoIter
type can't borrow from self
.
1 Like
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.