Skip to content

Conditionals

Accepted

Accepted for V1 brace-only conditional source forms and conditional expression values.

V1 if branches always use block braces. Single-expression branch syntax is deferred:

const x = if condition 1u32 else 2u32

if ... else ... can be an expression:

var x: i32 = if condition {
  1
} else {
  2
}

When if is used as a value, branches must have compatible types unless a branch diverges:

var x: i32 = if condition {
  1
} else {
  return .BadInput
}

An empty branch evaluates to void; normal type compatibility rules then apply.

An if without else has type void, including in value position:

const x = if ready {
  1u32
}

Here x has type void. The u32 branch value is discarded, which should produce a lint because an explicit else or else null is often intended. Assign the branch value to _ if discarding it is intentional.

const x: ?u32 = if ready {
  1u32
} else {
  null
}

Optional presence tests and payload binding are documented in Optional Bindings.

Comptime-Known Conditions

V1 does not have a separate comptime if source form. if is one source form. When its condition is compile-time-known, sema and lowering may evaluate the condition at compile time and keep only the reachable branch.

Compiler context values can be used this way:

if Compiler.safety_mode() == .Checked {
  _ = log_debug_state(state)
}

This is ordinary conditional syntax. It differs from a conditional declaration guard: a trailing declaration if controls whether a declaration participates in lookup, while a statement or expression if controls which branch executes or remains after compile-time evaluation.

Comptime-known conditions are evaluated under the active target and safety mode. See Comptime and Target and Safety Modes.