How can I implement a "default iterator" for a dash?

I am trying to implement a default iterator for structures that implement a trait. My dash called DataRow, represents a series of table cells and looks like this:

pub trait DataRow<'a> {
    // Gets a cell by index
    fn getCell(&self, i: usize) -> &DataCell<'a>;

    // Gets the number of cells in the row
    fn getNumCells(&self) -> usize;
}

The default iterator I want to provide should use these two methods to iterate over the string and return cell references. In Java, it comes down to an abstract class DataRowthat implements Iterable. In Rust, I first tried with IntoIterator:

impl<'a, T> IntoIterator for &'a T
where
    T: DataRow<'a>,
{
    type Item = &'a DataCell<'a>;
    type IntoIter = DataRowIterator<'a, T>;

    fn into_iter(self) -> DataRowIterator<'a, T> {
        return DataRowIterator::new(self);
    }
}

This does not work, since anyone can implement their own iterator for their own implementation DataRow.

My second attempt was to add a method iterto the attribute, which creates an iterator and returns it:

fn iter(&self) -> DataRowIterator<'a, Self> {
    return DataRowIterator::new(self);
}

, Self . DataRow , Sized .

-,

- " " ?

+5
1

IntoIterator IntoIterator .

impl<'a> IntoIterator for &'a DataRow<'a> {
    type Item = &'a DataCell<'a>;
    type IntoIter = DataRowIterator<'a>;

    fn into_iter(self) -> DataRowIterator<'a> {
        DataRowIterator::new(self)
    }
}

DataRowIterator , &DataRow &T , DataRow.

+4

Source: https://habr.com/ru/post/1688071/


All Articles