Constants
In V, in addition to variables, you can also create constants. Such constants can only be declared outside functions in the global scope.
Constants are declared with const
:
Multiple constants can be declared in one block:
The type of constant is automatically inferred from its value.
Constant names must be in snake_case
.
Constant values can never be changed.
V constants are more flexible than in most languages. You can assign more complex values:
Function calls in constants will be evaluated during program startup.
Constants inside modules
Like
other declarations,
constants can be declared public using the pub
keyword:
The pub
keyword is only allowed before the const
keyword and cannot be used inside
a const ( ... )
block.
Required module prefix
Outside from main
module all constants need to be prefixed with the module name.
In order to distinguish constants from local variables, the full path to constants must be specified.
For example, to access the pi
constant, full math.pi
name must be used both outside the math
module, and inside it.
That restriction is relaxed only for the main
module (the one containing your fn main()
),
where you can use the unqualified name of constants defined there, i.e. numbers
, rather
than main.numbers
.
vfmt takes care of this rule, so you can type println(pi)
inside the math
module, and vfmt will automatically update it to println(math.pi)
.