Macro match_class

Source
macro_rules! match_class {
    ($subject:expr, $($tt:tt)*) => { ... };
}
Expand description

Dispatches a class to different subclasses.

Similar to a match statement, but with downcasts. Earlier matches dominate, so keep more-derived classes first. The current implementation checks Gd::try_cast() linearly with the number of branches. This may change in the future.

When none of the listed classes match, a fallback branch acts as a catch-all and allows to retrieve the original Gd pointer. If the type of the match_class! expression is (), you can omit the fallback branch. For all other types, it is required, even if all direct subclasses are handled. The reason for this is that there may be other subclasses which are not statically known by godot-rust (e.g. from a script or GDExtension).

The fallback branch can either be _ (discard object), or variable to access the original object inside the fallback arm.

§Example

// Basic syntax.
let event: Gd<InputEvent> = some_input();

let simple_dispatch: i32 = match_class! { event,
   button @ InputEventMouseButton => 1,
   motion @ InputEventMouseMotion => 2,
   action @ InputEventAction => 3,
   key @ InputEventKey => 4,
   _ => 0, // Fallback.
};

// More diverse dispatch patterns are also supported.
let fancy_dispatch: i32 = match_class! { some_input(),
    // Mutable bindings supported:
    mut button @ InputEventMouseButton => 1,

    // Block syntax for multiple statements:
    motion @ InputEventMouseMotion => {
        godot_print!("motion");
        2
    },

    // Qualified types supported:
    action @ godot::classes::InputEventAction => 3,

    // If you're only interested in the class and not the object,
    // discard it with either `_` or `_variable`:
    _ @ InputEventKey => 4,

    // Fallback with variable -- retrieves original Gd<InputEvent>.
    original => 0,
    // Can also be used with mut:
    // mut original => 0,
    // If the match arms have type (), we can also omit the fallback branch.
};

// event_type is now 0, 1, 2, 3 or 4

§Expression and control flow

The match_class! macro is an expression, as such it has a type. If that type is not (), you typically need to use the expression or end it with a semicolon.

Control-flow statements like ?, return, continue, break can be used within the match arms.