Struct Deconstruction in parameter list

What is this syntax called? I found it browsing through the bevy source code, and i have never seen this:

fn on_insert(
    mut world: DeferredWorld, 
    HookContext { entity, caller, ..}: HookContext
) { ... }

HookContext:

#[derive(Clone, Copy, Debug)]
pub struct HookContext {
    pub entity: Entity,
    pub component_id: ComponentId,
    pub caller: Option<...>
}

I'm assuming that the function clones entity and caller, and leaves the default value for component_id. But is there more to it than this? Or is it just Syntactic Sugar?

That's a struct pattern that binds the entitry and caller fields to variables of the same name. This is known as destructuring, the variables being bound to the values of the struct via a move or, if the value implements Copy, via a copy. There is no implicit cloning.

2 Likes

Implicit in @jofas's response is the fact that function parameters (and let and for) are all patterns like those used in match. From the docs:

Patterns are used in:

In the case of function parameters, the pattern must be irrefutable (always able to match). The same is true for let without else, and for expressions. You may have even used some simple destructuring in those situations without thinking about it.

let (a, b) = (0, 1);
for (i, item) in iterator.enumerate() {}
5 Likes