Control Flow in Nyx
Nyx provides expressive, expression-oriented control flow primitives designed for predictable execution and high-performance compilation.
1. If / Else Expressions
In Nyx, if statements are expressions that evaluate to a value when used in assignment context:
let score = 85
let grade = if score >= 90 {
"A".to_string()
} else if score >= 80 {
"B".to_string()
} else {
"C".to_string()
}
std.io.println("Grade: " + grade)
2. While Loops
Use while loops to iterate as long as a boolean condition evaluates to true:
let mut count = 0
while count < 5 {
std.io.println("Count: " + count.to_string())
count = count + 1
}
3. For Loops & Iteration
Nyx provides concise for-in syntax across numeric ranges, vectors, and collections:
Range Iteration
// Exclusive upper bound (0 to 9)
for i in 0..10 {
std.io.println("Index: " + i.to_string())
}
Vector & Collection Iteration
let mut fruits = Vec.new()
fruits.push("Apple".to_string())
fruits.push("Banana".to_string())
fruits.push("Cherry".to_string())
for fruit in fruits {
std.io.println("Fruit: " + fruit)
}
Tuple & Destructuring Iteration
let mut coordinates = Vec.new()
coordinates.push((37.7749, -122.4194))
coordinates.push((34.0522, -118.2437))
for (lat, lon) in coordinates {
std.io.println("Lat: " + lat.to_string() + ", Lon: " + lon.to_string())
}
4. Pattern Matching with Match
Pattern matching in Nyx is exhaustive and operates over integers, strings, tuples, and algebraic data types (enums):
Enum Variant Matching
enum HttpStatus {
Ok,
NotFound,
ServerError(String),
}
let status = HttpStatus.ServerError("Database connection timed out".to_string())
match status {
HttpStatus.Ok => std.io.println("200 OK"),
HttpStatus.NotFound => std.io.println("404 Not Found"),
HttpStatus.ServerError(msg) => std.io.println("500 Error: " + msg),
}
Or-Patterns & Wildcards
let code = 403
match code {
200 | 201 => std.io.println("Success"),
400 | 401 | 403 | 404 => std.io.println("Client Error"),
500 | 502 | 503 => std.io.println("Server Error"),
_ => std.io.println("Unknown Status Code"),
}
5. Error Propagation with the Question Mark (?) Operator
Functions returning Result<T, E> or Option<T> can propagate failures cleanly using the ? operator:
import std.fs
import std.json
fn read_app_config(path: String) -> Result<json.Value, String> {
let content = fs.read_to_string(path)?
let parsed = json.parse(content)?
Result.Ok(parsed)
}
6. Early Returns & Loop Controls
Nyx supports standard break, continue, and return statements:
for i in 0..100 {
if i % 2 == 0 {
continue // Skip even numbers
}
if i > 15 {
break // Stop loop
}
std.io.println("Odd: " + i.to_string())
}