Modules in V

Posted by yhuang
Public (Editable by Users)
// V is a very modular language. Creating reusable modules is encouraged and is very simple.
// To create a new module, create a directory with your module's name and .v files with code:
// cd ~/code/modules
// mkdir mymodule
// vim mymodule/mymodule.v

// mymodule.v
module mymodule

// To export a function we have to use `pub`
pub fn say_hi() {
	println('hello from mymodule!')
// You can have as many .v files in mymodule/ as you want.
// Build it with v build module ~/code/modules/mymodule.

// That's it, you can now use it in your code:

module main

import mymodule

fn main() {
// Note that you have to specify the module every time you call an external function.
// This may seem verbose at first, but it makes code much more readable and easier to understand, since it's always clear which function from which module is being called. Especially in large code bases.
// Module names should be short, under 10 characters. Circular imports are not allowed.
// You can create modules anywhere.
// All modules are compiled statically into a single executable.
// If you want to write a module that will automatically call some setup/initialization code when imported (perhaps you want to call some C library functions), write a module init function inside the module:

fn init() int {
	// your setup code here ...
	return 1
// The init function cannot be public. It will be called automatically.