Skip to content

Prefer expressions to closures in #[require()] when defining required components #17584

Open
@jonathandw743

Description

@jonathandw743

This would improve #[require(...)]. It would make the interface align more with how people actually use it. It would also reduce repetition.

#[require()] should use expressions for the default value instead of closures or functions.
This is better explained using examples.

This:

#[derive(Component)]
#[require(
    MyOtherComponentA(|| MyOtherComponentA{x: 0.3, y: 0.5})
    MyOtherComponentA(|| MyOtherComponentA(100))
)]
struct Foo;

would become this:

#[derive(Component)]
#[require(
    MyOtherComponentA{x: 0.3, y: 0.5},
    MyOtherComponentA(100),
)]
struct Foo;

Any time you are using a closure with no arguments, the expression version is simpler.

This also has the side effect of meaning Default wouldn't have to be derived for unit structs, as Bar in #[require(Bar)] would just be the expression to use.

What if you want to use a function? Just call it:
This:

#[derive(Component)]
#[require(
    MyOtherComponentA(returns_component_a)
    MyOtherComponentA(returns_component_b)
)]
struct Foo;

would become this:

#[derive(Component)]
#[require(
    returns_component_a(),
    returns_component_b(),
)]
struct Foo;

You would have to confirm that the expressions are all of different types but I think that already happens.

If you wanted to maintain the current behaviour, you could do:

#[derive(Component)]
#[require(
    MyOtherComponentA::default()
    MyOtherComponentB::default()
)]
struct Foo;

Or the macro could try and use a default constructor if just the struct name is specified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-UsabilityA targeted quality-of-life change that makes Bevy easier to useD-MacrosCode that generates Rust codeD-ModestA "normal" level of difficulty; suitable for simple features or challenging fixesS-Ready-For-ImplementationThis issue is ready for an implementation PR. Go for it!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions