Variables, Constants and Mutability

4.1 Declaring Variables

:= declares. = assigns. All variables must be initialized.

No shadowing: redeclaring a name in an inner scope is a compile error.

Unused variables produce a warning (an error in -prod). Use _ to discard.

name := 'Bob'          // declare and initialize (type inferred); immutable
mut age := 20          // mutable
age = 21               // reassignment with `=` (only for mut)
x, y := 10, 20         // multiple declaration
mut a, mut b := 1, 2
a, b = b, a            // swap

4.2 Immutability by Default

Variables, function arguments, and struct fields are immutable unless declared mut.

This makes code easier to reason about and enables optimizations.

4.3 Constants

Constants are module-level. Reference them with their module prefix outside the module (math.pi).

const pi2 = 3.14159 * 2
const app_name = 'MyApp'
const (                 // grouped constants (older style; `v fmt` may rewrite to single const lines)
	max_users = 100
	version   = '1.0.0'
)
const primes = [2, 3, 5, 7]       // constants can be complex values
const config = Config{port: 8080} // even structs

4.4 Global Variables (Discouraged)

// requires: v -enable-globals run file.v
__global counter = 0