7. Documentation
Variables and Constants
Variables in Braid are declared with the let keyword. All variables are immutable by default and can be reassigned with =.
Variable Declaration
Use let followed by the variable name, optional type annotation, an = sign, and the initializer expression:
let x = 10
let name = "Braid"
let pi = 3.14159
let flag = true
let nothing = nilType Inference
Braid infers the type from the initializer. These declarations are equivalent:
let x = 42 // inferred as int
let x: int = 42 // explicit annotationExplicit Type Annotations
Add : type after the variable name to specify the type explicitly:
let count: int = 0
let price: float = 19.99
let greeting: string = "Hello"
let is_ready: bool = falseReassignment
Variables declared with let can be reassigned using =:
let counter = 0
counter = counter + 1 // reassignment
counter = 100 // new value
let name = "Alice"
name = "Bob"Multiple Variables
let a = 1
let b = 2
let c = 3
let result = a + b + c // 6Variables with Expressions
Initializers can be arbitrary expressions:
let x = 10
let y = x * 2 + 5 // 25
let z = y / 3 // 8 (integer division)
let sum = x + y + z
let message = "Total: " + sumVariables in Functions
Function parameters are variable bindings, and local variables work the same way:
fn calculate(a: int, b: int) -> int {
let sum = a + b
let product = a * b
let result = product - sum
return result
}Variable Scope
Variables declared inside a block {} are scoped to that block:
fn main() {
let outer = 10
if true {
let inner = 20
print(outer) // OK: outer is in scope
print(inner) // OK: inner is in scope
}
// print(inner) // Error: inner not in scope
}Shadowing
Braid allows variable shadowing in inner scopes:
let x = 10
if true {
let x = 20 // shadows outer x
print(x) // 20
}
print(x) // 10String Variables
let s1 = "Hello"
let s2 = "World"
let s3 = s1 + ", " + s2 // "Hello, World"Nil Variables
Variables can hold nil to represent the absence of a value:
let maybe: int = nil
let result = divide_safe(10.0, 0.0)
if result == nil {
print("failed")
}Common Patterns
// Accumulator pattern
let total = 0
total = total + 10
total = total + 20
print(total) // 30
// Flag pattern
let debug = true
if debug {
print("Debug mode enabled")
}
// Counter pattern
let i = 0
while i < 10 {
print(i)
i = i + 1
}