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.

Selective imports

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

  1. import os { input }
  2. import crypto.sha256 { sum }
  3. import time { Time }

Note: 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. import crypto.sha256
  2. import mymod.sha256 as mysha256
  3. fn main() {
  4. v_hash := sha256.sum('hi'.bytes()).hex()
  5. my_hash := mysha256.sum('hi'.bytes()).hex()
  6. assert my_hash == v_hash
  7. }

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

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