This repository has been archived on 2025-08-04. You can view files and clone it, but cannot push or open issues or pull requests.
rhaj/_archive/rhai_engine/rhaibook/language/switch-expression.md
2025-04-04 08:28:07 +02:00

748 B

Switch Expression

{{#include ../links.md}}

Like [if], [switch] also works as an expression.


This means that a [`switch`] expression can appear anywhere a regular expression can,
e.g. as [function] call arguments.

[`switch`] expressions can be disabled via [`Engine::set_allow_switch_expression`][options].
let x = switch foo { 1 => true, _ => false };

func(switch foo {
    "hello" => 42,
    "world" => 123,
    _ => 0
});

// The above is somewhat equivalent to:

let x = if foo == 1 { true } else { false };

if foo == "hello" {
    func(42);
} else if foo == "world" {
    func(123);
} else {
    func(0);
}