I'm trying to write a tree in rust, here is the Node:
#[derive(Debug)]
struct Node<'a> {
player_id: i8,
visits : i32,
score : i32,
children : Vec<Node<'a>>,
parent: Option<&'a mut Node<'a>>,
action: usize,
}
impl Node<'_> {
pub fn is_leaf(&self) -> bool {
return self.children.is_empty()
}
}
I am trying to add children for every move possible in game:
fn expand_children <'a>(node: & 'a mut Node<'a>, game : &GameState) {
game.legal_moves().iter().for_each(
|action|
node.children.push(
Node::<'a> {
parent: Some(node),
action : *action,
player_id: game.curr_player(),
visits: 0,
score: 0,
children: vec![]
}
)
)
}
This is the error I get:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/MCTS.rs:59:25
|
59 | parent: Some(node),
| ^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined here...
--> src/MCTS.rs:56:9
|
56 | / |action|
57 | | node.children.push(
58 | | Node::<'a> {
59 | | parent: Some(node),
... |
65 | | }
66 | | )
| |_________^
note: ...so that closure can access `node`
--> src/MCTS.rs:59:30
|
59 | parent: Some(node),
| ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/MCTS.rs:54:21
|
54 | fn expand_children <'a>(node: & 'a mut Node<'a>, game : &GameState) {
| ^^
note: ...so that the expression is assignable
--> src/MCTS.rs:59:25
|
59 | parent: Some(node),
| ^^^^^^^^^^
= note: expected `Option<&'a mut Node<'a>>`
found `Option<&mut Node<'a>>`
I thought I did set the lifetime of node as 'a in the function parameters as its &'a mut Node<'a>
. How is it possible that the compiler does not find it on compiletime? Or am I missing something.. I know that the error message should tell me whats wrong but I dont think I understand it very well..