Modules

Every file in the root of a folder is part of the same module. Simple programs don’t need to specify module name, in which case it defaults to ‘main’.

V is a very modular language. Creating reusable modules is encouraged and is quite easy to do. To create a new module, create a directory with your module’s name containing .v files with code:

1. cd ~/code/modules
2. mkdir mymodule
3. vim mymodule/myfile.v
1. // myfile.v
2. module mymodule

4. // To export a function we have to use `pub`
5. pub fn say_hi() {
6. println('hello from mymodule!')
7. }

You can now use mymodule in your code:

1. import mymodule

3. fn main() {
4. mymodule.say_hi()
5. }
  • Module names should be short, under 10 characters.
  • Circular imports are not allowed.
  • You can have as many .v files in a module as you want.
  • You can create modules anywhere.
  • All modules are compiled statically into a single executable.

init functions

If you want a module to automatically call some setup/initialization code when it is imported, you can use a module init function:

1. fn init() {
2. // your setup code here ...
3. }

The init function cannot be public - it will be called automatically. This feature is particularly useful for initializing a C library.