Module imports

For information about creating a module, see Modules.

Modules can be imported using the import keyword:

  1. import os
  2. fn main() {
  3. // read text from stdin
  4. name := os.input('Enter your name: ')
  5. println('Hello, $name!')
  6. }

This program can use any public definitions from the os module, such as the input function. See the standard library documentation for a list of common modules and their public symbols.

By default, you have to specify the module prefix every time you call an external function. This may seem verbose at first, but it makes code much more readable and easier to understand - it’s always clear which function from which module is being called. This is especially useful in large code bases.

Cyclic module imports are not allowed, like in Go.

Selective imports

You can also import specific functions and types from modules directly:

  1. import os { input }
  2. fn main() {
  3. // read text from stdin
  4. name := input('Enter your name: ')
  5. println('Hello, $name!')
  6. }

Note: This will import the module as well. Also, this is not allowed for constants - they must always be prefixed.

You can import several specific symbols at once:

  1. import os { input, user_os }
  2. name := input('Enter your name: ')
  3. println('Name: $name')
  4. os := user_os()
  5. println('Your OS is ${os}.')

Module import aliasing

Any imported module name can be aliased using the as keyword:

NOTE: this example will not compile unless you have created mymod/sha256.v

  1. // failcompile
  2. import crypto.sha256
  3. import mymod.sha256 as mysha256
  4. fn main() {
  5. v_hash := sha256.sum('hi'.bytes()).hex()
  6. my_hash := mysha256.sum('hi'.bytes()).hex()
  7. assert my_hash == v_hash
  8. }

You cannot alias an imported function or type. However, you can redeclare a type.

  1. import time
  2. import math
  3. type MyTime = time.Time
  4. fn (mut t MyTime) century() int {
  5. return int(1.0 + math.trunc(f64(t.year) * 0.009999794661191))
  6. }
  7. fn main() {
  8. mut my_time := MyTime{
  9. year: 2020
  10. month: 12
  11. day: 25
  12. }
  13. println(time.new_time(my_time).utc_string())
  14. println('Century: $my_time.century()')
  15. }