If I want to implement iterators for a custom struct in Rust, do I have to copy the code…
- User
If I want to implement iterators for a custom struct in Rust, do I have to copy the code three times for the owning, shared and mutable versions, or is there a way to reuse the code?
Assistant
In Rust, you don't need to copy the iterator implementation code three separate times for owning, shared (
&), and mutable (&mut) iterators. Instead, you can leverage generics and traits to write a single implementation that works for all three cases. This approach promotes code reuse and reduces duplication.How to Achieve Code Reuse
-
Define a Generic Iterator Struct: Create a generic struct for your iterator that can hold references with different lifetimes and mutability levels.
-
Implement the Iterator Trait Generically: Implement the
Iteratortrait for your generic iterator struct. Use Rust's powerful type system to handle the differences between owned, shared, and mutable variants. -
Provide Associated Functions or Methods: Define methods on your custom struct that return the appropriate iterator types based on ownership and mutability.
Example Implementation
Let's walk through an example where we have a custom struct
MyCollectionand want to provide owning, shared, and mutable iterators without duplicating code.// Define the custom collection struct pub struct MyCollection<T> { items: Vec<T>, } impl<T> MyCollection<T> { // Constructor pub fn new(items: Vec<T>) -> Self { MyCollection { items } } // Method to get an owning iterator pub fn into_iter(self) -> IntoIter<T> { IntoIter { inner: self.items.into_iter(), } } // Method to get a shared iterator pub fn iter(&self) -> Iter<'_, T> { Iter { inner: self.items.iter(), } } // Method to get a mutable iterator pub fn iter_mut(&mut self) -> IterMut<'_, T> { IterMut { inner: self.items.iter_mut(), } } } // Define the owning iterator pub struct IntoIter<T> { inner: std::vec::IntoIter<T>, } impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } } // Define the shared iterator pub struct Iter<'a, T> { inner: std::slice::Iter<'a, T>, } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } } // Define the mutable iterator pub struct IterMut<'a, T> { inner: std::slice::IterMut<'a, T>, } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } }Explanation
-
Generic Iterator Structs:
IntoIter<T>holds anstd::vec::IntoIter<T>, which is the owning iterator over the vector.Iter<'a, T>holds anstd::slice::Iter<'a, T>, which is the shared iterator over a slice.IterMut<'a, T>holds anstd::slice::IterMut<'a, T>, which is the mutable iterator over a slice.
-
Iterator Implementations:
- Each iterator struct implements the
Iteratortrait, specifying the appropriateItemtype (T,&'a T, or&'a mut T). - The
nextmethod simply delegates to the inner iterator'snextmethod.
- Each iterator struct implements the
-
Associated Methods in
MyCollection:into_iterconsumes the collection and returns anIntoIter.iterborrows the collection immutably and returns anIter.iter_mutborrows the collection mutably and returns anIterMut.
Leveraging
std::iter::IteratorTraitsRust's standard library provides iterator adaptors and combinators that work seamlessly with any type implementing the
Iteratortrait. By defining your custom iterators as shown, they integrate naturally with the rest of the Rust ecosystem.Advanced: Using a Single Generic Iterator (Optional)
If you prefer even more abstraction, you can define a single generic iterator struct that handles all three cases using enums or additional generics. However, this approach can become complex and may not offer significant advantages over the straightforward method shown above.
Here's a simplified example using enums:
pub enum MyIterator<'a, T> { Owned(std::vec::IntoIter<T>), Borrowed(std::slice::Iter<'a, T>), BorrowedMut(std::slice::IterMut<'a, T>), } impl<'a, T> Iterator for MyIterator<'a, T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { match self { MyIterator::Owned(iter) => iter.next(), // Note: You'll need to adjust Item types accordingly _ => unimplemented!(), } } }However, managing the different
Itemtypes (T,&T,&mut T) within a single enum can complicate the implementation. Therefore, sticking with separate iterator structs as initially shown is often clearer and more maintainable.Conclusion
By defining separate but similar iterator structs for each type of iteration (owning, shared, mutable) and implementing the
Iteratortrait for each, you avoid code duplication while maintaining clarity and leveraging Rust's strong type system. This pattern aligns well with idiomatic Rust practices and ensures that your custom iterators are both efficient and easy to use.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.