Avatar ·

Cómo implementar los traits Iterator e IntoIterator para una estructura simple en Rust

¡Hola a todos! He empezado a aprender Rust y me encontré con un problema al implementar iteradores personalizados. Tengo una estructura simple `BookCollection` que almacena una lista de libros. Quiero que esta estructura se pueda usar en un bucle `for`, así como pasarla a funciones que esperan iteradores. Pero el compilador da errores. Aquí está mi código: ```rust struct Book { title: String, author: String, } struct BookCollection { books: Vec, } impl BookCollection { fn new() -> Self { BookCollection { books: Vec::new() } } fn add_book(&mut self, book: Book) { self.books.push(book); } } fn main() { let mut collection = BookCollection::new(); collection.add_book(Book { title: "1984".to_string(), author: "Orwell".to_string() }); collection.add_book(Book { title: "Dune".to_string(), author: "Herbert".to_string() }); // Quiero hacer esto: for book in collection { println!("{} by {}", book.titl