Skip to main content

Mojo function

global_constant

global_constant[T: AnyType, //, value: T]() -> ref [StaticConstantOrigin] T

Creates a reference to a compile-time constant value stored in static memory.

This function stores the compile-time constant in the binary's read-only data section and returns a reference to it, avoiding runtime materialization. This is useful for large lookup tables where you want to access individual elements without copying the entire structure onto the stack.

Examples:

from builtin.globals import global_constant

# Create a reference to a constant array and access elements
comptime lookup_table = InlineArray[Int, 4](1, 2, 3, 4)
var element = global_constant[lookup_table]()[2]  # Access without materializing entire array
print(element)  # Prints: 3

# Use with more complex compile-time values
fn compute(x: Int) -> Int:
    return x * 2 + 1

comptime data = InlineArray[Int, 3](1, compute(5), 100)
ref data_ref = global_constant[data]()
print(data_ref[0], data_ref[1], data_ref[2])  # Prints: 1 11 100

Constraints:

The type T must be trivially register-passable. Self-contained types like Int, SIMD, and InlineArray work. Types with heap allocations like Dict, List, or String do not work because their internal pointers would be invalid at runtime. Using unsupported types will result in a compilation error.

Parameters:

  • T (AnyType): The type of the constant value. Must be trivially register-passable.
  • value (T): The compile-time constant value.

Returns:

ref: A reference to the global constant with StaticConstantOrigin.

Was this page helpful?