Reputation: 197
So I'm trying to squeeze in callbacks to this enum variant (Visual
) - which will be stored in a vector as seen within the struct EntityComponents
:
enum Component {
Position([f64; 2]),
Visual(& Fn(Entity) -> ()),
}
struct EntityComponents {
components_of_entity: HashMap<TypeId, Vec<Component>>,
}
However, Rust requires me to provide explicit lifetime parameters here.
My idea is that I want the function reference to live at least as long as its argument (the Entity
), but I have no idea how the syntax for that would look like? Is it even possible?
The idea is that as long as an Entity
has a Visual
component, we can use this callback to render it!
Upvotes: 5
Views: 838
Reputation: 89006
A few things:
&Fn()
instead of fn()
. The former is a trait object of the Fn
trait, the latter is a good ol' function pointer. While the former is more general (in particular, it supports closures), it's rather unusual to store a reference to a closure that lives somewhere else.
Box<Fn()>
which solves your lifetime problems.Visual(fn(Entity)),
. Function pointer always have a static lifetime. So this solves your lifetime problems as well.Fn
trait object, which lives somewhere else? The solution depends on where it lives:Entity
: see here<'a>
Fn(Entity) -> ()
. The -> ()
is always useless, you can omit it.Upvotes: 4