How to Use Trait Properly

Hi, I tried to simulate iter and iter_mut functions but couldn't use traits properly.

Here are my struct and functions. How can I iter them with traits ?

pub struct NeuralLayer {
    neural_layer: Vec<Neuron>,
}

impl NeuralLayer {
    pub fn iter(&self) -> std::slice::Iter<Neuron> {
        self.neural_layer.iter()
    }

    pub fn iter_mut(&mut self) -> std::slice::IterMut<Neuron> {
        self.neural_layer.iter_mut()
    }
}

I don’t see anything wrong so far, but I also don’t quite understand your question— Can you give a little bit more information about what output you’re looking for, or the things you’ve tried that didn’t work?

2 Likes

If you want &NeuralLayer and &mut NeuralLayer to work with for (or with IntoIterator trait bounds), the trait you're looking for is IntoIterator.

By convention, .iter() corresponds to impl<'a> IntoIterator for &'a Struct and .iter_mut() corresponds to impl<'a> IntoIterator for &'a mut Struct.

impl<'a> IntoIterator for &'a NeuralLayer {
    type IntoIter = std::slice::Iter<'a, Neuron>;
    type Item = &'a Neuron;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &'a mut NeuralLayer {
    type IntoIter = std::slice::IterMut<'a, Neuron>;
    type Item = &'a mut Neuron;
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

If you also want an owning iterator, that would just be impl Iterator for NeuralLayer (and by convention, consumers would call the trait method .into_iter() directly).

7 Likes

I think @quinedot answered your question, but just in case: Are you asking how you can return an impl Iterator<...> so that you're not referencing the slice iterator types? Like this:

impl NeuralLayer {
    pub fn iter(&self) -> impl Iterator<Item = &Neuron> {
        self.neural_layer.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Neuron> {
        self.neural_layer.iter_mut()
    }
}
3 Likes

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.