Repository navigation
Match and Type Guards
A match evaluates its subject once and selects the first matching arm. Each arm
has a body scope, and its final result becomes the match's value.
let $priority = 4
let $expected = 9
let $description = match $priority
{
0 => { "idle" }
1..5 => { "routine" }
$expected => { "reserved" }
_ => { "urgent" }
}
echo $description
routine
Patterns can be literals, ranges, enum values, variables holding values or ranges,
and ranges whose bounds are variables. .. excludes its end and ..= includes
it. _ is an optional last fallback. Without a matching arm or fallback, match
raises a runtime error rather than returning a guessed default.
Every value has .type. Type names are values, and Type.name gives the name
represented by a Type object. Identity tests are exact: a named Integer wrapper
has its own type, and Number is not a wildcard type test.
let $reading: any = 12
match $reading.type
{
Integer => { echo ($reading + 1) }
String => { echo $reading.trim }
_ => { echo "other reading" }
}
if $reading.type == Integer && $reading > 10 { echo warm }
13
warm
The checker narrows a variable inside a matching type arm and along a true
short-circuit && path. It can use the refined type to check arithmetic and
member access. Named union interfaces can also narrow to a concrete member;
unions explains which methods become available.
For absence, compare the value with () or its type with None. () is a value,
not a synonym for the Type object named None.
Related: Enums · Control flow · Reflection
Begin here
Values and expressions
- Language basics
- Variables and scope
- Numbers and logic
- Strings and paths
- Arrays
- Hash maps
- Ranges and iteration
- Control flow
- Match and type guards
Functions and types
- Functions and calls
- Closures and function types
- Methods and properties
- Structs
- Enums
- Named types and unions
- Conversions
- Types and properties
Shell and modules
- Pipelines
- Pipeline splits
- Pipeline formats
- Commands and exit status
- Redirection
- Environment and exported variables
- Modules and visibility
- Nested modules and directory packages
- Conditional imports and declarations
- Errors and cleanup
- Supervised processes and terminals
Library guides
- Standard library
- The implicit prelude
- Bytes, files, readers, and writers
- Explicit item streams
- JSON documents and typed mapping
- Sockets, DNS, and TLS
- HTTP clients
- HTTP servers
- Framing, server-sent events, and JSON-RPC
- Terminal colors, styles, and geometry
- Build an application console
Interactive use