bevy_lint::lints

Module panicking_methods

Source
Expand description

Checks for use of panicking methods of Query, QueryState, or World when a non-panicking alternative exists.

For instance, this will lint against Query::single(), recommending that Query::get_single() should be used instead.

This lint is actually two: PANICKING_QUERY_METHODS and PANICKING_WORLD_METHODS. Each can be toggled separately. The query variant lints for Query and QueryState, while the world variant lints for World.

§Motivation

Panicking is the nuclear option of error handling in Rust: it is meant for cases where recovery is near-impossible. As such, panicking is usually undesirable in long-running applications and games like what Bevy is used for. This lint aims to prevent unwanted crashes in these applications by forcing developers to handle the Option or Result in their code.

§Example

#[derive(Component)]
struct MyComponent;

#[derive(Resource)]
struct MyResource;

fn panicking_query(query: Query<&MyComponent>) {
    let component = query.single();
    // ...
}

fn panicking_world(world: &mut World) {
    let resource = world.resource::<MyResource>();
    // ...
}

Use instead:

#[derive(Component)]
struct MyComponent;

#[derive(Resource)]
struct MyResource;

fn graceful_query(query: Query<&MyComponent>) {
    match query.get_single() {
        Ok(component) => {
            // ...
        }
        Err(error) => {
            error!("Invariant not upheld: {:?}", error);
            return;
        }
    }
}

fn graceful_world(world: &mut World) {
    let Some(resource) = world.get_resource::<MyResource>() else {
        // Resource may not exist.
        return;
    };

    // ...
}

Structs§

Statics§