Skip to main content

Variables and Constants

Mux supports both explicit type declarations and type inference with the auto keyword.

Variable Declarations

Explicit Typing

variables.mux
Loading...

Type Inference with auto

type_inference.mux
Loading...

Important Rules

variable_rules.mux
Loading...

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:

uninitialized_declaration.mux
Loading...

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:

read_before_assignment.mux
Loading...

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:

constants.mux
Loading...

Const Enforcement

  • Cannot reassign: const_var = new_value -> ERROR
  • Cannot use compound assignment: const_var += 1 -> ERROR
  • Cannot increment/decrement: const_var++ or const_var-- -> ERROR
  • Applies to both identifiers and class fields
  • Use const when you want a value that won't change after initialization

When to Use auto

  • Local variables with obvious initialization
  • Complex generic types that are clear from context
  • Temporary variables in calculations
  • Iterator variables in loops
explicit_types.mux
Loading...

Using Underscore for Unused Values

The underscore _ is a placeholder for values you don't need:

underscore.mux
Loading...

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:

scope.mux
Loading...

Unless you create a closure, then you can capture variables from the enclosing scope:

closure_scope.mux
Loading...

See Also

  • Types - Type system and conversions
  • Functions - Function declarations
  • Classes - Class fields and constants