如何在Rust中为简单结构实现Iterator和IntoIterator特性?
大家好!我开始学习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