Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen-max-2025-01-25· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

If I want to implement iterators for a custom struct in Rust, do I have to copy the code…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. 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?

  2. Qwen 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

    1. Define a Generic Iterator Struct: Create a generic struct for your iterator that can hold references with different lifetimes and mutability levels.

    2. Implement the Iterator Trait Generically: Implement the Iterator trait for your generic iterator struct. Use Rust's powerful type system to handle the differences between owned, shared, and mutable variants.

    3. 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 MyCollection and 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

    1. Generic Iterator Structs:

      • IntoIter<T> holds an std::vec::IntoIter<T>, which is the owning iterator over the vector.
      • Iter<'a, T> holds an std::slice::Iter<'a, T>, which is the shared iterator over a slice.
      • IterMut<'a, T> holds an std::slice::IterMut<'a, T>, which is the mutable iterator over a slice.
    2. Iterator Implementations:

      • Each iterator struct implements the Iterator trait, specifying the appropriate Item type (T, &'a T, or &'a mut T).
      • The next method simply delegates to the inner iterator's next method.
    3. Associated Methods in MyCollection:

      • into_iter consumes the collection and returns an IntoIter.
      • iter borrows the collection immutably and returns an Iter.
      • iter_mut borrows the collection mutably and returns an IterMut.

    Leveraging std::iter::Iterator Traits

    Rust's standard library provides iterator adaptors and combinators that work seamlessly with any type implementing the Iterator trait. 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 Item types (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 Iterator trait 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.