I'm building a little program to learn rust. I'm trying to make snake.
Snake consists of snake parts. Those snake parts work like linked list, each snake part knows which snake part is the previous one. Snake itself knows where is it's head and tail. It looks like this:
pub struct Snake<'a> {
head: &'a SnakePart<'a>,
tail: &'a SnakePart<'a>,
}
struct SnakePart<'a> {
x: f32,
y: f32,
previous_part: Option<&'a SnakePart<'a>>,
}
However I have problems writing Snake constructor. So far I have this:
impl<'a> Snake<'a> {
pub fn new(x: f32, y: f32) -> Snake<'a> {
let snake_part: SnakePart<'a> = SnakePart::new(x, y);
Snake {
head: &snake_part,
tail: &snake_part,
current_angle: 0.,
}
}
}
This creates snake, which has only one segment (or snake part), and it's both his tail and head. However this doesn't compile. Compiler tells me that snake_part
only lives to the end of constructor, and it has to live for the lifetime 'a
as defined on the impl
block.
I know that it has to live as long as the whole snake, but why this does not work? I would think that the snake part will live while the snake itself live - the snake I return has lifetime 'a
. How can I persuade Rust to let snake parts live long enough?
I tried to save all snake parts into the snake structure itself. So I changed it this way:
pub struct Snake<'a> {
...
snake_parts: Vec<SnakePart<'a>>,
}
impl<'a> Snake<'a> {
let snake_part: SnakePart<'a> = SnakePart::new(x, y);
let mut snake_parts: Vec<SnakePart<'a>> = Vec::with_capacity(1);
snake_parts.push(snake_part);
Snake {
head: &snake_parts[0],
tail: &snake_parts[0],
snake_parts: snake_parts,
current_angle: 0.,
}
}
Why this doesn't work? (It has exactly the same problem as the previous code). I take the snake part, push it into vector full of snake parts, and the vector itself is saved into the snake. Why doesn't it live long enough?