Constants

  1. const (
  2. pi = 3.14
  3. world = '世界'
  4. )
  5. println(pi)
  6. println(world)

Constants are declared with const. They can only be defined at the module level (outside of functions). Constant values can never be changed. You can also declare a single constant separately:

  1. const e = 2.71828

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

  1. struct Color {
  2. r int
  3. g int
  4. b int
  5. }
  6. fn rgb(r int, g int, b int) Color {
  7. return Color{
  8. r: r
  9. g: g
  10. b: b
  11. }
  12. }
  13. const (
  14. numbers = [1, 2, 3]
  15. red = Color{
  16. r: 255
  17. g: 0
  18. b: 0
  19. }
  20. // evaluate function call at compile-time*
  21. blue = rgb(0, 0, 255)
  22. )
  23. println(numbers)
  24. println(red)
  25. 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:

  1. // oksyntax
  2. module mymodule
  3. pub const golden_ratio = 1.61803
  4. fn calc() {
  5. println(mymodule.golden_ratio)
  6. }

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

Outside from module main all constants need to be prefixed with the module name.

Required module prefix

When naming constants, snake_case must be used. In order to distinguish consts from local variables, the full path to consts must be specified. For example, to access the PI const, 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).