Module imports

For information about creating a module, see Modules.

Modules can be imported using the import keyword:

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

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:

import os { input } fn main() { // read text from stdin name := input('Enter your name: ') println('Hello, ${name}!') }

[!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:

import os { input, user_os } name := input('Enter your name: ') println('Name: ${name}') current_os := user_os() println('Your OS is ${current_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/somename.v (submodule names are determined by their path, not by the names of the .v file(s) in them).

import crypto.sha256 import mymod.sha256 as mysha256 fn main() { v_hash := sha256.sum('hi'.bytes()).hex() my_hash := mysha256.sum('hi'.bytes()).hex() assert my_hash == v_hash }

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

import time import math type MyTime = time.Time fn (mut t MyTime) century() int { return int(1.0 + math.trunc(f64(t.year) * 0.009999794661191)) } fn main() { mut my_time := MyTime{ year: 2020 month: 12 day: 25 } println( println('Century: ${my_time.century()}') }