Constants (v0.2.1)

Compile-time values that cannot be reassigned.

Latest

Overview

Constants define values known at compile time. They are useful for sizes, flags, protocol values, and other numbers that should not be repeated throughout the code.

Constants can be built from compile-time helpers such as sizeOf and alignOf. That keeps layout-related values tied to the type they describe.

Use constants when the value is part of the program definition, not something that changes at runtime.

Primary source: syntax/constants/

Syntax Signatures

const U32_SIZE: usize = sizeOf(u32);
const F64_ALIGN: u32 = alignOf(f64);
const READY: bool = true;

Behavior and Use

A constant cannot be reassigned. The compiler can use the value directly wherever the constant is referenced.

Keep constants near the code or module they describe. Very large global constant files are harder to maintain.

Best Practices

Compile-Time Values

Constants are resolved while the program is compiled.

Constants Versus Variables

Use constants when the value is a rule, not state.

Example

const BUFFER_CAPACITY: usize = 1024;

fn capacity() usize @public {
    return BUFFER_CAPACITY;
}

Back to language reference