Conditionals#
if runs a block when a Bool condition is true; else runs otherwise.
Save this as status.ms and run ms run status.ms:
fn status(active Bool) String {
if active {
return "Active"
} else {
return "Inactive"
}
}
fn main() Void {
print(status(true))
print(status(false))
}Active
InactiveA short branch can be one simple statement on the same line:
fn status(active Bool) String {
if active { return "Active" }
return "Inactive"
}See the block rules
for one-line blocks and else chains.
- Conditions must be
Bool; numbers and text have no truth values. ifis a statement here; the expression form is below .- The condition is evaluated once; at most one branch runs.
else ifandelsefollow the closing brace on its line:} else if c {,} else {.- Each branch has its own scope; assignments to an outer
varpersist. - An
else ifchain tests in order and stops at the first match.
fn classify(value Int) String {
if value < 0 {
return "negative"
} else if value == 0 {
return "zero"
} else {
return "positive"
}
}if 1 { ... } is rejected: the condition must be Bool.
If as an expression#
if c { a } else { b } is an expression when it appears where a value is expected. Both branches are single expressions of one type, else is required, and else if chains:
fn sign(value Int) Int {
return if value < 0 { - 1 } else if value == 0 { 0 } else { 1 }
}The branches are one-line expressions on the same line. For statements in a branch, use an if statement or a match arm. The return rules
still require every reachable path of a function to return.
Unwrapping an Optional or Result#
if name := expression { ... } runs its block when a Result
is ok, binding name immutably inside the block. else runs for an error, where name is not visible. A Result’s error is not captured; use ? or err() when it matters. The expression evaluates once. An Optional
is tested with != null instead, which makes the name its payload inside the block (if name != null { ... }); if name := optional is rejected with that remedy.
fn greeting(name String?) String {
if name != null {
return "Hello, " + name
} else {
return "Hello!"
}
}fn port(lookup Result[Int, Error]) Int {
if value := lookup {
return value
}
return 8080
}if var name = place[key]? { ... } borrows a map or list entry in place. place[key]? is the entry when it exists, and name is a mutable borrow of it. place[key]? is written only here.
if var entry = entries[key]? { ... }thenentry.count = entry.count + 1changes the value inentries.if var n = counts[key]? { n += 1 }updatescountswithout copying a scalar.- A missing key or out-of-range index takes the
elsebranch. - The origin must be
var, and nothing else may use it until the last use ofname. if var name = map.get(key) { ... }also borrows the map entry in place.- For other expressions,
if varcan take an owned payload (including from a local at its last use), but cannot mutably borrow an arbitraryOptional. To change an independent copy, bindv := x, testv != null, and clone the payload into avar.
This complete test updates an existing map entry:
import expect_equal from "@std/test/test.ms"
test "increment a visit count" {
var counts = {"visits": 2}
if var count = counts.get("visits") {
count += 1
}
expect_equal(counts.get_or("visits", 0), 3)?
}A present 0, false, or empty string still takes the first branch. The binding is one name; destructure inside the block. Prefer v != null to a two-arm match on a payload name and null (MSL108).
Validating inputs#
Validate with an early return:
fn nonnegative(value Int) Bool {
if value < 0 {
return false
}
return true
}Expected failures uses this shape to reject invalid input with a domain error.
Bindings after a branch#
To select a value for use after the conditional, use an if expression (label := if active { "Active" } else { "Inactive" }), or declare an outer var when branches perform multiple statements before assigning. See bindings
. Use pattern matching
to branch on the case of an enum.