Am i correctly implementing Iterators for a my custom Vector struct?
⚓ Rust 📅 2025-10-22 👤 surdeus 👁️ 3Hello, everyone
I have been working on my first rust project and the first part of this project was implementing a Vector struct.While writing the implementation for Vector i had some trouble implementing Iterators and after some struggle i got the code to work. I just wanted to see if this a good way to implement iterators for custom structs?
pub struct Vector<T: Float> {
pub i: T, // i-hat component
pub j: T, // j-hat component
pub k: T, // k-hat component
}
pub struct Iter<'a, T: Float> {
inner: &'a Vector<T>,
index: u8
}
pub struct IntoIter<T: Float> {
inner: Vector<T>,
index: u8
}
pub struct IterMut<'a, T: Float> {
inner: *mut Vector<T>,
index: u8,
_phantom: PhantomData<&'a mut Vector<T>>
}
impl<'a, T: Float> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let to_return = match self.index {
0 => Some(&self.inner.i),
1 => Some(&self.inner.j),
2 => Some(&self.inner.k),
_ => None
};
self.index += 1;
to_return
}
}
impl<T:Float> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let to_return = match self.index {
0 => Some(self.inner.i),
1 => Some(self.inner.j),
2 => Some(self.inner.k),
_ => None
};
self.index += 1;
to_return
}
}
impl<'a, T: Float> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
let to_return = match self.index {
0 => Some( unsafe {&mut (*self.inner).i} ),
1 => Some( unsafe {&mut (*self.inner).j} ),
2 => Some( unsafe {&mut (*self.inner).k} ),
_ => None
};
self.index += 1;
to_return
}
}
impl<'a, T: Float> IntoIterator for &'a Vector<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
Iter{
inner: self,
index: 0
}
}
}
impl<T: Float> IntoIterator for Vector<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
inner: self,
index: 0
}
}
}
impl<'a, T: Float> IntoIterator for &'a mut Vector<T> {
type Item = &'a mut T;
type IntoIter = IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
IterMut{
inner: self,
index: 0,
_phantom: PhantomData
}
}
}
2 posts - 2 participants
🏷️ Rust_feed