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'.

See symbol visibility, Access modifiers.

Create modules

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:

cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v
// myfile.v module mymodule // To export a function we have to use `pub` pub fn say_hi() { println('hello from mymodule!') }

All items inside a module can be used between the files of a module regardless of whether or not they are prefaced with the pub keyword.

// myfile2.v module mymodule pub fn say_hi_and_bye() { say_hi() // from myfile.v println('goodbye from mymodule') }

You can now use mymodule in your code:

import mymodule fn main() { mymodule.say_hi() mymodule.say_hi_and_bye() }
  • Module names should be short, under 10 characters.
  • Module names must use snake_case.
  • 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.

Special considerations for project folders

For the top level project folder (the one, compiled with v .), and only that folder, you can have several .v files, that may be mentioning different modules with module main, module abc etc

This is to ease the prototyping workflow in that folder:

  • you can start developing some new project with a single .v file
  • split functionality as necessary to different .v files in the same folder
  • when that makes logical sense to be further organised, put them into their own directory module.

Note that in ordinary modules, all .v files must start with module name_of_folder.

init functions

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

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

The init function cannot be public - it will be called automatically by V, just once, no matter how many times the module was imported in your program. This feature is particularly useful for initializing a C library.

cleanup functions

If you want a module to automatically call some cleanup/deinitialization code, when your program ends, you can define a module cleanup function:

fn cleanup() { // your deinitialisation code here ... }

Just like the init function, the cleanup function for a module cannot be public - it will be called automatically, when your program ends, once per module, even if the module was imported transitively by other modules several times, in the reverse order of the init calls.