Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::iter;
- #[derive(Debug)]
- struct Book {
- pub title: String,
- }
- #[derive(Debug)]
- struct Library {
- pub books: Vec<Book>,
- }
- #[derive(Debug)]
- struct LibraryIterator<'b> {
- /// Keeps track which index we're currently at.
- pub cursor: usize,
- /// Borrow of the Bookshelf we're going to iterate over.
- pub inner: &'b Library,
- }
- #[derive(Debug)]
- struct LibraryIter {
- /// Borrow of the Bookshelf we're going to iterate over.
- pub inner: Library,
- }
- impl Library {
- /// Create an iterator that iterates over all books in the library.
- pub fn iter(&self) -> LibraryIterator {
- LibraryIterator {
- inner: self,
- cursor: 0,
- }
- }
- }
- impl<'b> iter::Iterator for LibraryIterator<'b> {
- type Item = &'b Book;
- fn next(&mut self) -> Option<Self::Item> {
- let cursor = self.cursor;
- self.cursor += 1;
- if cursor >= self.inner.books.len() {
- None
- } else {
- Some(&self.inner.books[cursor])
- }
- }
- }
- impl iter::Iterator for LibraryIter {
- type Item = Book;
- fn next(&mut self) -> Option<Self::Item> {
- if self.inner.books.len() > 0 {
- Some(self.inner.books.remove(0))
- } else {
- None
- }
- }
- }
- impl<'b> iter::IntoIterator for &'b Library {
- type Item = &'b Book;
- type IntoIter = LibraryIterator<'b>;
- fn into_iter(self) -> Self::IntoIter {
- Self::IntoIter {
- cursor: 0,
- inner: self,
- }
- }
- }
- impl<'b> iter::IntoIterator for Library {
- type Item = Book;
- type IntoIter = LibraryIter;
- fn into_iter(self) -> Self::IntoIter {
- Self::IntoIter {
- inner: self,
- }
- }
- }
- fn main() {
- let library = Library {
- books: vec![
- Book { title: "Das Kapital I".into() },
- Book { title: "Das Kapital II".into() },
- Book { title: "Das Kapital III".into() },
- ],
- };
- // Borrow library and iterate.
- for book in library.iter() {
- println!("book {}", book.title);
- }
- // Consume library and iterate. `library` can no longer be used after this
- // point.
- for book in &library {
- println!("book {}", book.title);
- }
- for book in library {
- println!("book {}", book.title);
- }
- }
Add Comment
Please, Sign In to add comment