3.0k

The V Programming Language

Simple, fast, safe language created for developing Volt, soon available for everyone.

Open source release in June 2019. Early access since April 15.
Install V from source in 0.5 seconds
wget vlang.io/v.c && gcc -o v v.c
Subscribe to development updates

Introduction

V is a statically typed compiled programming language designed for building maintainable software.

It's similar to Go and is also influenced by Oberon, Rust, Swift.

V is a very simple language. Going through this documentation will take you about half an hour, and by the end of it you will learn pretty much the entire language.

Despite being simple, it gives a lot of power to the developer. Anything you can do in other languages, you can do in V.

Found an error/typo? Please submit a pull request.

Hello World

fn main() {
	println('hello world')
}

Functions are declared with fn. Return type goes after the function name. In this case main doesn't return anything, so the type is omitted.

Just like in C and all related languages, main is an entry point.

println is one of the few builtin functions. It prints the value to standard output.

fn main() declaration can be skipped in one file programs. This is useful when writing small programs, "scripts", or just learning the language. For brevity, fn main() will be skipped in this tutorial.

This means that a "hello world" program can be as simple as

println('hello world')

Comments

// This is a single line comment.

/* This is a multiline comment.
   /* It can be nested. */
*/

Functions

fn main() {
	println(add(77, 33))
	println(sub(100, 50))
}

fn add(x int, y int) int {
	return x + y
}

fn sub(x, y int) int {
	return x - y
}

Again, the type comes after the argument's name.

Just like in Go and C, functions cannot be overloaded. This simplifies the code and improves maintainability and readability.

Functions can be used before their declaration: add and sub are declared after main, but can still be called from main. This is true for all declarations in V and eliminates the need of header files or thinking about the order of files and declarations.

Variables

name := 'Bob' 
age := 20
large_number := i64(9999999999)
println(name)
println(age)
println(large_number) 

Variables are declared and initialized with :=. This is the only way to declare variables in V. This means that variables always have an initial value.

The variable's type is inferred from the value on the right hand side. To force a different type, use type conversion: the expression T(v) converts the value v to the type T.

Unlike most other languages, V only allows defining variables in functions. Global (module level) variables are not allowed. There's no global state in V.

 

mut age := 20
println(age)
age = 21
println(age)

To change the value of the variable use =. In V variables are immutable by default. To be able to change the value of the variable, you have to declare it with mut.

Try compiling the program above after removing mut from the first line.

Please note the difference between := and =
:= is used for declaring and initializing, = is used for assigning.

 

fn main() {
	age = 21
}

This code will not compile, because variable age is not declared. All variables need to be declared in V.

Unused variables result in a compilation error.

Basic types

bool

string

i8  i16  i32  i64
u8  u16  u32  u64 

byte // alias for u8  
int  // alias for i32  
rune // alias for i32, represents a Unicode code point  

f32 f64
Please note, than unlike C and Go, int is always a 32 bit integer.

Strings

name := 'Bob' 
println('Hello, $name!') 
println(name.len) 

bobby := name + 'by' // + is used to concatenate strings 
println(bobby) // ==> "Bobby"  

println(bobby.substr(1, 3)) // ==> "ob"  
// println(bobby[1:3]) // This syntax will most likely replace the substr() method   

In V, a string is a read-only array of bytes. String data is encoded using UTF-8.

Strings are immutable. This means that the substring function is very efficient: no copying is performed, no extra allocations required.

Concatenation operator + needs to have strings on both sides. This code will not compile if age is an int:

println('age = ' + age)
We have to either convert age to a string:
println('age = ' + age.str())
or use string interpolation (preferred):
println('age = $age')

Arrays

nums := [1, 2, 3]
println(nums)
println(nums[1]) // ==> "2" 

mut names := ['John']
names << 'Peter' 
names << 'Sam' 
// names << 10  <-- This will not compile. `names` is an array of strings. 
println(names.len) // ==> "3" 
println('Alex' in names) // ==> "false" 

// We can also preallocate a certain amount of elements. 
nr_ids := 50
mut ids := [0 ; nr_ids] // This creates an array with 50 zeroes 

Array type is determined by the first element: [1, 2, 3] is an array of ints
([]int).
['a', 'b'] is an array of strings ([]string).

All elements must have the same type. [1, 'a'] will not compile.

<< is an operator that appends a value to the end of the array.

.len field returns the length of the array. Note, that it's a read-only field, and it can't be modified by the user. All exported fields are read-only by default in V.

val in array returns true if the array contains val.

Maps

mut m := map[string]int{} // Only maps with string keys are allowed for now  
m['one'] = 1
println(m['one']) // ==> "1"  
println(m['bad_key']) // ==> "0"  
// TODO: implement a way to check if the key exists 

numbers := { // TODO: this syntax is not implemented yet  
	'one': 1,
	'two': 2,
} 

If

a := 10 
b := 20 
if a < b { 
	println('$a < $b') 
} else if a > b { 
	println('$a > $b') 
} else { 
	println('$a == $b') 
} 

if statements are pretty straightforward and similar to most other languages.

Unlike other C-like languages, there are no parentheses surrounding the condition, and the braces are always required.

if can be used as an expression:

num := 777
s := if num % 2 == 0 {
	'even'
}
else {
	'odd'
}
println(s) // ==> "odd"

For loop

V has only one looping construct: for.
numbers := [1, 2, 3, 4, 5]
for num in numbers {
	println(num)
}
names := ['Sam', 'Peter']
for i, name in names {
	println('$i) $name')  // Output: 0) Sam
}                             //         1) Peter

The for .. in loop is used for going through elements of an array. If an index is required, an alternative form for index, value in can be used.

 

mut sum := 0
mut i := 0
for i <= 100 {
	sum += i
	i++
}
println(sum) // ==> "5050" 

This form of the loop is similar to while loops in other languages.

The loop will stop iterating once the boolean condition evaluates to false.

Again, there are no parentheses surrounding the condition, and the braces are always required.

 

mut num := 0
for {
	num++
	if num >= 10 {
		break 
	} 
}
println(num) // ==> "10" 

The condition can be omitted, this results in an infinite loop.

 

for i := 0; i < 10; i++ {
	println(i)
}

Finally, there's the traditional C style for loop. It's safer than the `while` form because with the latter it's easy to forget to update the counter and get stuck in an infinite loop.

Here i doesn't need to be declared with mut since it's always going to be mutable by definition.

Switch

os := 'windows' 
print('V is running on ')
switch os {
case 'darwin':
	println('macOS.')
case 'linux':
	println('Linux.')
default:
	println(os) 
}
// TODO: replace with match expressions 

A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.

Unlike C, break statement is not needed at the end of every block.

Structs

struct Point {
	x int
	y int 
} 

p := Point{
	x: 10 
	y: 20 
} 
println(p.x) // Struct fields are accessed using a dot 

 

Structs are allocated on the stack. To allocate a struct on the heap and get a pointer to it, use the & prefix:

pointer := &Point{10, 10}  // Alternative initialization syntax for structs with 3 fields or fewer
println(pointer.x) // Pointers have the same syntax for accessing fields  

 

V doesn't have subclassing, but it supports embedded structs:

// TODO: this will be implemented later in May
struct Button {
	Widget
	title string
}

button := new_button('Click me')
button.set_pos(x, y)

// Without embedding we'd have to do
button.widget.set_pos(x,y)

Methods

struct User {
	age int 
} 

fn (u User) can_register() bool {
	return u.age > 16 
} 

user := User{age: 10} 
println(user.can_register()) // ==> "false"  

user2 := User{age: 20} 
println(user2.can_register()) // ==> "true"  

V doesn't have classes. But you can define methods on types.

A method is a function with a special receiver argument.

The receiver appears in its own argument list between the fn keyword and the method name.

In this example, the can_register method has a receiver of type User named u. The convention is not to use receiver names like self or this, but a short, preferably one letter long, name.

Pure functions by default

V functions are pure by default, meaning that their return values are only determined by their arguments, and their evaluation has no side effects.

This is achieved by lack of global variables and all function arguments being immutable by default, even when references are passed.

V is not a pure functional language however. It is possible to modify function arguments by using the same keyword mut:

struct User {
	is_registered bool 
} 

fn (u mut User) register() {
	u.is_registered = true 
} 

mut user := User{} 
println(user.is_registered) // ==> "false"  
user.register() 
println(user.is_registered) // ==> "true"  

In this example the receiver (which is simply the first argument) is marked as mutable, so register() can change the user object. The same works with non-receiver arguments:

fn multiply_by_2(arr mut []int) {
	for i := 0; i < arr.len; i++ {
		arr[i] *= 2
	}
}

mut nums := [1, 2, 3]
multiply_by_2(mut nums)
println(nums) // ==> "[2, 4, 6]"

Note, that you have to add mut before nums when calling this function. This makes it clear that the function being called will modify the value.

It is preferable to return values instead of modifying arguments. Modifying arguments should only be done in performance-critical parts of your application to reduce allocations and copying.

Use user.register() or user = register(user) instead of register(mut user).

V makes it easy to return a modifed version of an an object:

// TODO: this syntax is not implemented yet  
fn register(u User) User { 
	return { u | is_registered: true } 
}

user = register(user) 

Constants

const (
	PI    = 3.14
	World = '世界'
) 

println(PI)
println(World)

Constants are declared with const. They can only be defined at the module level (outside of functions).

Constant names must be capitalized. This helps distinguish them from variables.

Constant values can never be changed.

V constants are more flexible than in most languages. You can assign more complex values:

struct Color {
        r int
        g int
        b int
}

fn (c Color) str() string { return '{$c.r, $c.g, $c.b}' }

fn rgb(r, g, b int) Color { return Color{r: r, g: g, b: b} }

const (
        Numbers = [1, 2, 3]

        Red  = Color{r: 255, g: 0, b: 0}
        Blue = rgb(0, 0, 255)
)

println(Numbers)
println(Red)
println(Blue)

Global variables are not allowed, so this can be really useful.

Modules

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 -lib ~/code/modules/mymodule.

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

module main

import mymodule

fn main() {
	mymodule.say_hi()
}

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.

Right now you can create modules anywhere, perhaps this should be standardized (like Go's GOPATH).

All modules are compiled statically into a single executable.

Interfaces

struct Dog {}
struct Cat {}

fn (d Dog) speak() string { 
	return 'woof'
} 

fn (c Cat) speak() string { 
	return 'meow' 
} 

interface Speaker {
	speak() string
}

fn perform(s Speaker) { 
	println(s.speak())
} 

dog := Dog{} 
cat := Cat{} 
perform(dog) // ==> "woof" 
perform(cat) // ==> "meow" 

A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword.

Enums

enum Color {
	red green blue 
} 

mut color := Color.red
// V knows that color is a Color. No need to use `Color.green` here.
color = .green 
println(color) // ==> "1"  TODO: print "green"?  

Option/Result types & error handling

struct User {
	id int 
} 

struct Repo {
	users []User 
} 

fn new_repo() Repo {
        user := User{id:10}
        return Repo {
                users: [user]
        }
} 

fn (r Repo) find_user_by_id(id int) User? { 
	for user in r.users {
		if user.id == id {
			// V automatically wraps this into an option type  
			return user 
		} 
	} 
	return error('User $id not found') 
} 

repo := new_repo() 
user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks  
	return  // `or` block must end with `return`, `break`, or `continue`  
} 
println(user.id) // ==> "10"  

V combines Option and Result into one type, so you don't need to decide which one to use.

The amount of work required to "upgrade" a function to an optional function is minimal: you have to add a ? to the return type and return an error when something goes wrong.

If you don't need to return an error, you can simply return None. (TODO: None is not implemented yet).

This is the primary way of handling errors in V. They are still values, like in Go, but the advantage is that errors can't be unhandled, and handling them is a lot less verbose.

You can also propagate errors:

resp := http.get(url)?
println(resp.body)
http.get returns ?http.Response. It was called with ?, so the error is propagated to the calling function or in case of main leads to a panic.

Basically the code above is a shorter version of

resp := http.get(url) or {
	panic(err)
}
println(resp.body)

Generics (July)

struct Repo<T> {
	db DB
}

fn new_repo<T>(db DB) Repo<T> {
	return Repo<T>{db: db}
}

// This is a generic function. V will generate it for every type it's used with. 
fn (r Repo<T>) find_by_id(id int) ?T {  
	table_name := T.name // in this example getting the name of the type gives us the table name 
	return r.db.query_one<T>('select * from $table_name where id = ?', id)
}

db := new_db()
users_repo := new_repo<User>(db)
posts_repo := new_repo<Post>(db)
user := users_repo.find_by_id(1)? 
post := posts_repo.find_by_id(1)? 

Concurrency

The concurrency model is very similar to Go. To run foo() concurrently, just call it with go foo(). Right now it launches the function in a new system thread, soon goroutines and the scheduler will be implemented.

Decoding JSON

struct User {
	name string
	age  int 
} 

data := '{ "name": "Frodo", "age": 25 }'
user := json.decode(User, data) or {
	eprintln('Failed to decode json')
	return 
} 
println(user.name)
println(user.age) 

JSON is very popular nowadays, that's why JSON support is built in.

The first argument of the json.decode function is the type to decode to. The second argument is the json string.

V generates code for json encoding and decoding. No runtime reflection is used. This results in much better performance.

Reflection via codegen

Having builtin JSON support is nice, but V also allows you to create effecient serializers for anything:
// TODO: planned in May
fn decode<T>(data string) T {
        mut result := T{}
        for field in T.fields {
                if field.typ == 'string' {
                        result.$field = get_string(data, field.name)
                } else if field.typ == 'int' {
                        result.$field = get_int(data, field.name)
                }
        }
        return result
}

// generates to:
fn decode_User(data string) User {
        mut result := User{}
        result.name = get_string(data, 'name')
        result.age = get_int(data, 'age')
        return result
}

Limited operator overloading

struct Vec {
	x int
	y int
}

fn (a Vec) str() string { 
	return '{$a.x, $a.y}' 
}

fn (a Vec) + (b Vec) Vec {
	return Vec {
		a.x + b.x, 
		a.y + b.y 
	}
}

fn (a Vec) - (b Vec) Vec {
	return Vec {
		a.x - b.x, 
		a.y - b.y
	}
}

fn main() { 
	a := Vec{2, 3}
	b := Vec{4, 5}
	println(a + b) // ==> "{6, 8}"  
	println(a - b) // ==> "{-2, -2}"  
} 

Operator overloading goes against V's philosophy of simplicity and predictability. But since scientific and graphical applications are among V's domains, operator overloading is very important to have in order to improve readability:

a.add(b).add(c.mul(d)) is a lot less readable than a + b + c * d.

To improve safety and maintainability, operator overloading has several limitations:

- It's only possible to overload +, -, *, / operators.
- Calling other functions inside operator functions is not allowed.
- Operator functions can't modify their arguments.

Testing

// hello.v 
fn hello() string {
	return 'Hello world'
} 

// hello_test.v 
fn test_hello() {
    assert hello() == 'Hello world'
} 
All test functions have to be placed in *_test.v files and begin with test_. To run the tests do v hello_test.v. To test an entire module do v test mymodule.

Memory management

There's no garbage collection or reference counting. V cleans up what it can during compilation. For example:
fn draw_text(s string, x, y int) {
	...
}

fn draw_scene() {
	draw_text('hello $name1', 10, 10)
	draw_text('hello $name2', 100, 10)
	draw_text(strings.repeat('X', 10000), 10, 50)
}
The strings don't escape draw_text, so they are cleaned up when the function exits.

In fact the first two calls won't result in any allocations at all. These two strings ('hello' and 'world') are small, V will use a preallocated buffer for them.

For more complex cases manual memory management is required. This will be fixed soon.

V will detect memory leaks at runtime and report them. To clean up, for example, an array, use the free() method:

numbers := [0; 1000000] 
...
numbers.free()

Calling C functions from V

#flag -lsqlite3

#include "sqlite3.h"

struct C.sqlite3 
struct C.sqlite3_stmt 

fn C.sqlite3_column_int(C.sqlite_stmt, int) int 

fn main() {
	path := 'sqlite3_users.db' 
	db := &C.sqlite3{} 
	C.sqlite3_open(path.cstr(), &db)

	query := 'select count(*) from users' 
	stmt := &C.sqlite3_stmt{} 
	C.sqlite3_prepare_v2(db, query.cstr(), - 1, &stmt, 0)
	C.sqlite3_step(stmt) 
	nr_users := C.sqlite3_column_int(res, 0)
	C.sqlite3_finalize(res)
	println(nr_users) 
} 

Translating C/C++ to V

V can translate your C/C++ code to human readable V code. Let's create a simple program test.cpp first:
#include <vector>
#include <string>
#include <iostream>

int main() {
        std::vector<std::string> s;
        s.push_back("V is ");
        s.push_back("awesome");
        std::cout << s.size() << std::endl;
        return 0;
} 
Run v translate test.cpp and V will generate test.v:
fn main {
        mut s := []
	s << 'V is '
	s << 'awesome'
	println(s.len) 
} 

An online C/C++ to V translator is coming soon.

Hot code reloading

TODO

Cross compilation

To cross compile your project simply run
v -os windows .
or
v -os linux .
(Cross compiling for macOS is temporarily not possible.)

If you don't have any C dependencies, that's all you need to do. This works even when compiling GUI apps using the ui module or graphical apps using gg.

Appendix I: Keywords

V has 21 keywords:
break 
const  
continue 
defer 
else 
enum 
fn
for
go
goto
if
import
in 
interface 
match 
module 
mut 
or 
return
struct
type