Variables and Constants
Mux supports both explicit type declarations and type inference with the auto keyword.
Variable Declarations
Explicit Typing
Type Inference with auto
Important Rules
auto needs an initializer, because there is nothing else to infer the type
from. An explicit type does not. Semicolons are not used.
Declaring Without a Value
A declaration with an explicit type may omit the initializer, and be assigned later:
This is what keeps a function flat when it makes several fallible calls. The
alternative is a match nested inside a match for each one, indenting the
real work further at every step.
It matters most for types with no natural zero value. A string could be
declared as "" and overwritten, but a class type has nothing to stand in -
there is no empty TcpListener - so without this the value could not leave the
arm that produced it.
Reading such a variable before it is assigned is a compile error, not a default value:
The check is flow-sensitive: it follows every path to the read. A variable
assigned in an if with no else is not assigned on all paths, and neither is
one assigned in only some arms of a match. Every branch must either assign it
or leave (return, or otherwise not reach the read).
Constants
Constants are immutable values that cannot be reassigned or modified after initialization:
Const Enforcement
- Cannot reassign:
const_var = new_value-> ERROR - Cannot use compound assignment:
const_var += 1-> ERROR - Cannot increment/decrement:
const_var++orconst_var---> ERROR - Applies to both identifiers and class fields
- Use
constwhen you want a value that won't change after initialization
When to Use auto
Recommended
- Local variables with obvious initialization
- Complex generic types that are clear from context
- Temporary variables in calculations
- Iterator variables in loops
Explicit Types Recommended
Using Underscore for Unused Values
The underscore _ is a placeholder for values you don't need:
Best Practice: Use _ when a value is required by syntax but not needed in your code. Don't overuse it when descriptive names would improve readability.
Variable Scope
Variables are scoped to the block in which they are declared:
Unless you create a closure, then you can capture variables from the enclosing scope: