I am trying to implement a display_snakes() function that will print every Snake within a SnakePool struct. Issue is that SnakePool nor Snake can implement Copy, and Iterator is not implemented for SnakePool. I have tried implementing Copy on both, and Iterator on SnakePool but am not clear on exactly how to do it correctly. I do not want the display_snakes() function to consume the SnakePool struct or the Snakes within.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Point {
pub latitude: Latitude,
pub longitude: Longitude,
}
impl Point {
pub fn new() -> Self {
let mut rng = rand::thread_rng();
Self {
latitude: Latitude::new(&mut rng),
longitude: Longitude::new(&mut rng)
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Snake {
id: Option<u32>,
point: Point,
body: Vec<Point>,
collapse: bool,
}
impl Snake {
pub fn new(id: u32) -> Self {
Self { id: Some(id), point: Point::new(), body: vec![], collapse: false }
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SnakePool {
snakes: Vec<Snake>
}
impl SnakePool {
pub fn new() -> Self {
Self {
snakes: {
let mut snakes = Vec::new();
for n in 0..10 {
let snake = Snake::new(n);
snakes.push(snake);
}
snakes
}
}
}
pub fn display_snakes(self) {
for snake in self {
println!("Snake: {:?}", snake)
}
}
}
fn main() {
let snake_pool = SnakePool::new();
snake_pool.display_snakes();
}
Error Code:
error[E0277]: `&SnakePool` is not an iterator
--> src\snake_pool.rs:23:22
|
23 | for snake in self {
| ^^^^ `&SnakePool` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&SnakePool`
= note: required for `&SnakePool` to implement `IntoIterator`