PSA: You can use match (true) with pattern guards instead of if-else

Hello
For reference: GDScript reference — Godot Engine (stable) documentation in English

If, like me, you’re finding expansive, many-branched if-else statements not readable enough, consider this

if (x == 0):
    print("equal to 0")
elif (x > 0):
    print("greater than 0")
else:
    print("smaller than 0")

As an equivalent of

match true:
    _ when x == 0:
        print("equal to 0")

    _ when x > 0:
        print("greater than 0")

    _:
        print("smaller than 0")

I don’t know about the performance differences, but i’d like to think they’re mostly the same, as it functions just as syntactic sugar.
Please rip me a new one if i’m wrong.

2 Likes

The parentheses in the if statement are optional, just like in Python.

1 Like