Constants

A constant can be qualified with its module name inside that module, including in module tests.

A fixed array constant can be initialized by a function call; the call runs during initialization.

const pi = 3.14 const world = '世界' println(pi) println(world)

Constants are declared with const. They can only be defined at the module level (outside of functions). Global variables can infer their types from constants, including constants initialized by functions. Global pointers to fixed-array literals are initialized at startup, including nested elements computed by function calls.

Constant values can never be changed. You can also declare a single constant separately:

const e = 2.71828

A constant initializer may call a function with the same name, such as const answer = answer(). Reading the constant itself in its initializer is still a cycle.

V constants are more flexible than in most languages. You can assign more complex values:

struct Color { r int g int b int } fn rgb(r int, g int, b int) Color { return Color{ r: r g: g b: b } } const numbers = [1, 2, 3] const red = Color{ r: 255 g: 0 b: 0 } // evaluate function call at compile time* const blue = rgb(0, 0, 255) println(numbers) println(red) println(blue)

* WIP - for now function calls are evaluated at program start-up

Global variables are not normally allowed, so this can be really useful.

Modules

Constants can be made public with pub const:

module mymodule pub const golden_ratio = 1.61803 fn calc() { println(golden_ratio) }

The pub keyword is only allowed before the const keyword and cannot be used inside a const ( ) block.

Constants can be referenced without a module prefix from within the module where they are defined. To access a public constant from another module, prefix it with the module name.

Required module prefix

When naming constants, snake_case must be used. Outside the module where a constant is defined, its full path must be specified. For example, use math.pi to access the public pi constant from another module. Inside the math module, the unqualified name pi can be used.

On this page