كيفية تنفيذ traits Iterator و IntoIterator لهيكل بسيط في Rust؟
مرحباً بالجميع! بدأت تعلم Rust وواجهت مشكلة عند تنفيذ المكررات الخاصة بي. لدي هيكل بسيط `BookCollection` يخزن قائمة من الكتب. أريد أن يكون هذا الهيكل قابلاً للاستخدام في حلقة `for`، وكذلك تمريره إلى دوال تنتظر مكررات. لكن المترجم يعطي أخطاء.
إليك الكود الخاص بي:
```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() });
// أريد أن أفعل هكذا:
for book in collection {
println!("{} by {}", book.titl