var (Mutable Bindings)
The var keyword is used to create mutable bindings, where the bound value can be reassigned in subsequent code. When you need to count, accumulate results, or update state, using var is the appropriate choice.
Variables modified with var can be assigned multiple times, and each assignment changes the value held by the variable. The assignment operator = is used to modify the variable's value, requiring the type of the right-hand expression to be a subtype of the left-hand variable's type. Cangjie does not support chained assignment (like a = b = 0), which helps avoid common coding errors.
The code on the right demonstrates typical usage of var: count starts at 0 and is modified multiple times; message changes from "hello" to "world". After each assignment, we print the variable's new value to observe the changes.
let by default, and only switch to var when you're certain you need to modify the variable. This reduces bugs from accidental modifications.Try changing one of the var to let and observe what error message the compiler gives. Then think about which variables truly need mutability.