Closed d0rianb closed 1 year ago
Hi @d0rianb, I think what you're trying to do is forbidden by Rust.
struct Context<'ctx> {
blocks: Vec<Block>,
selected_block: &'ctx Block,
}
In Rust, self-referential structs are forbidden -- in other words, it's not possible to have a struct hold a reference to a thing which is also in that struct. I'd recommend changing this to:
struct Context {
blocks: Vec<Rc<Block>>,
selected_block: Rc<Block>,
}
Or alternatively, selected_block
could be an integer or other ID, which shows which block in the Vec
is selected.
Ok I will try this but I don't think it's a self-referential struct because selected_block
refer to a Block not to the context.
I think a self-referential struct just means any struct which has a reference to either itself, or something inside itself.
To give a specific example of the safety issue, let's say you set self.selected_block
to &self.blocks[0]
, and then delete all the elements in self.blocks
. This would mean self.selected_block
now points to something which doesn't exist (i.e. a dangling reference).
Ok I understand I will implement the Rc solution, thanks
I can't figure out how to use references in struct belonging to the
WindowHandler
because of lifetime errors :error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement'
. TheWindowHandler
lifetime is suppose to be static because it lives as long as the program lives but there is no way to specify it to the compiler. I try by changing the'static
lifetime on theContext
into anonymous but it's still the same error. Is it any solution ? A simple replication of my issue is down below :