V Programming Language
V Programming Language
Calling C functions from V Compile time if Reflection via codegen Limited operator overloading Inline assembly Translating C/C++ to V Hot code reloading
Cross compilation Cross-platform shell scripts in V
Appendix I: Keywords Appendix II: Operators
Introduction
V is a statically typed compiled programming language designed for building maintainable software.
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.
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.
println is one of the few built-in functions. It prints the value to standard output.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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.
Comments
// This is a single line comment.
Functions
fn main() {
println(add(77, 33))
println(sub(100, 50))
}
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.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
fn foo() (int, int) {
return 2, 3
}
a, b := foo()
println(a) // 2
println(b) // 3
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.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
fn main() {
age = 21
}
This code will not compile, because variable age is not declared. All variables need to be declared in V.
fn main() {
age := 21
}
In development mode this code will result in an "unused variable" warning. In production mode ( v -prod foo.v ) it will not compile at all, like in Go.
fn main() {
a := 10
if true {
a := 20
}
}
Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name that is already used in a parent scope will result in a compilation
error.
Basic types
bool
string
f32 f64
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
byteptr
voidptr
Please note that unlike C and Go, int is always a 32 bit integer.
Strings
name := 'Bob'
println('Hello, $name!') // `$` is used for string interpolation
println(name.len)
Both single and double quotes can be used to denote strings. For consistency, vfmt converts double quotes to single quotes unless the string contains a single
quote character.
Interpolation syntax is pretty simple. It also works with fields: 'age = $user.age' . If you need more complex expressions, use ${} : 'can register = ${user.age >
13}' .
All operators in V must have values of the same type on both sides. This code will not compile if age is an int :
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
println('age = ' + age.str())
a := `a`
assert 'aloha!'[0] == `a`
s := r'hello\nworld'
println(s) // "hello\nworld"
Arrays
mut nums := [1, 2, 3]
println(nums) // "[1, 2, 3]"
println(nums[1]) // "2"
nums << 4
println(nums) // "[1, 2, 3, 4]"
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
ids := [0].repeat(50) // This creates an array with 50 zeros
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. It can also append an entire 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.
All arrays can be easily printed with println(arr) and converted to a string with s := arr.str() .
Maps
mut m := map[string]int // Only maps with string keys are allowed for now
m['one'] = 1
m['two'] = 2
println(m['one']) // "1"
println(m['bad_key']) // "0"
println('bad_key' in m) // Use `in` to detect whether such key exists
m.delete('two')
numbers := {
'one': 1,
'two': 2,
}
If
a := 10
b := 20
if a < b {
println('$a < $b')
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
} else if a > b {
println('$a > $b')
} else {
println('$a == $b')
}
Unlike other C-like languages, there are no parentheses surrounding the condition, and the braces are always required.
num := 777
s := if num % 2 == 0 {
'even'
}
else {
'odd'
}
println(s) // "odd"
In operator
in allows to check whether an array or a map contains an element.
nums := [1, 2, 3]
println(1 in nums) // true
m := {'one': 1, 'two': 2}
println('one' in m) // true
It's also useful for writing more clear and compact boolean expressions:
if parser.token == .plus || parser.token == .minus ||
parser.token == .div || parser.token == .mult {
...
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
V optimizes such expressions, so both if statements above produce the same machine code, no arrays are created.
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 value 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.
Note, that the value is read-only. If you need to modify the array while looping, you have to use indexing:
mut numbers := [1, 2, 3, 4, 5]
for i, num in numbers {
println(num)
numbers[i] = 0
}
mut sum := 0
mut i := 0
for i <= 100 {
sum += i
i++
}
println(sum) // "5050"
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.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
mut num := 0
for {
num++
if num >= 10 {
break
}
}
println(num) // "10"
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.
Match
os := 'windows'
print('V is running on ')
match os {
'darwin' => { println('macOS.') }
'linux' => { println('Linux.') }
else => { println(os) }
}
A match statement is a shorter way to write a sequence of if - else statements. When a matching branch is found, the expression following the => will be
evaluated. The else => branch will be evaluated when no other branches match.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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 reference to it, use the & prefix:
The type of p is &Point . It's a reference to Point . References are similar to Go pointers and C++ references.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Access modifiers
Struct fields are private and immutable by default (making structs immutable as well). Their access modifiers can be changed with pub and mut . In total, there
are 5 possible options:
struct Foo {
a int // private immutable (default)
mut:
b int // private mutable
c int // (you can list multiple fields with the same access modifier)
pub:
d int // public immmutable (readonly)
pub mut:
e int // public, but mutable only in parent module
pub mut mut:
f int // public and mutable both inside and outside parent module
} // (not recommended to use, that's why it's so verbose)
For example, here's the string type defined in the builtin module:
struct string {
str byteptr
pub:
len int
}
It's easy to see from this definition that string is an immutable type.
The byte pointer with the string data is not accessible outside builtin at all. len field is public, but not mutable.
fn main() {
str := 'hello'
len := str.len // OK
str.len++ // Compilation error
}
Methods
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
struct User {
age int
}
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.
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 {
mut:
is_registered bool
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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
}
}
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.
user = register(user)
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
fn main() {
println(run(5, sqr)) // "25"
}
References
fn (foo Foo) bar_method() {
...
}
fn bar_function(foo Foo) {
...
}
If a function argument is immutable like foo in the examples above, V can pass it by value or by reference. The decision is made by the compiler, and the
developer doesn't need to think about it.
You no longer need to remember whether you should pass the struct by value or by reference.
There's a way to ensure that the struct is always passed by reference by adding & :
fn (foo &Foo) bar() {
println(foo.abc)
}
foo is still immutable and can't be changed. For that, (foo mut Foo) has to be used.
In general, V references are similar to Go pointers and C++ references. For example, a tree structure definition would look like this:
struct Node<T> {
val T
left &Node
right &Node
}
Constants
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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).
V constants are more flexible than in most languages. You can assign more complex values:
struct Color {
r int
g int
b int
}
const (
numbers = [1, 2, 3]
println(numbers)
println(red)
println(blue)
When naming constants, snake_case must be used. Many people prefer all caps consts: TOP_CITIES . This wouldn't work well in V, because consts are a lot
more powerful than in other languages. They can represent complex structures, and this is used quite often since there are no globals:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
println('Top cities: $TOP_CITIES.filter(.usa)')
vs
println('Top cities: $top_cities.filter(.usa)')
println
println is a simple yet powerful builtin function. It can print anything: strings, numbers, arrays, maps, structs.
println(1) // "1"
println('hi') // "hi"
println([1,2,3]) // "[1, 2, 3]"
println(User{name:'Bob', age:20}) // "User{name:'Bob', age:20}"
If you want to define a custom print value for your type, simply define a .str() string method.
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
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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.
Interfaces
struct Dog {}
struct Cat {}
interface Speaker {
speak() string
}
fn perform(s Speaker) {
println(s.speak())
}
dog := Dog{}
cat := Cat{}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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
}
struct Repo {
users []User
}
fn new_repo() Repo {
return Repo {
users: [User{1, 'Andrew'}, User {2, 'Bob'}, User {10, 'Charles'}]
}
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
return error('User $id not found')
}
fn main() {
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"
println(user.name) // "Charles"
}
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 .
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.
err is defined inside an or block and is set to the string message passed to the error() function. err is empty if none was returned.
user := repo.find_user_by_id(7) or {
println(err) // "User 7 not found"
return
}
http.get returns ?http.Response . It was called with ? , so the error is propagated to the calling function (which must return an optional) or in case of main
leads to a panic.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
}
println(resp.body)
V does not have a way to force unwrap an optional (like Rust's unwrap() or Swift's ! ). You have to use or { panic(err) } instead.
Generics
struct 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 coroutines and the scheduler will be implemented.
Decoding JSON
import json
struct User {
name string
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
age int
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.
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_ .
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Memory management
(Work in progress) There's no garbage collection or reference counting. V cleans everything up during compilation. If your V program compiles, it's guaranteed
that it's going to be leak free. 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 are small, V will use a preallocated buffer for them.
fn test() []int {
number := 7 // stack variable
user := User{} // struct allocated on stack
numbers := [1, 2, 3] // array allocated on heap, will be freed as the function exits
println(number)
println(user)
println(numbers)
numbers2 := [4, 5, 6] // array that's being returned, won't be freed here
return numbers2
}
Defer
A defer statement defers the execution of a block of statements until the surrounding function returns.
fn read_log() {
f := os.open('log.txt')
defer { f.close() }
...
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
if !ok {
// defer statement will be called here, the file will be closed
return
}
...
// defer statement will be called here, the file will be closed
}
ORM
(alpha)
V has a built-in ORM that supports Postgres, and will soon support MySQL and SQLite.
One syntax for all SQL dialects. Migrating to a different database becomes much easier.
Queries are constructed with V syntax. There's no need to learn another syntax.
Safety. It's impossible to construct a SQL query with an injection.
Compile time checks. No more typos that can only be caught at runtime.
Readability and simplicity. You don't need to manually parse the results and construct objects.
struct Customer { // struct name has to be the same as the table name for now
id int // an integer id must be the first field
name string
nr_orders int
country string
}
db := pg.connect(db_name, db_user)
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
}
vfmt
You don't need to worry about formatting your code or style guidelines. vfmt takes care of that:
v fmt file.v
It's recommended to set up your editor, so that vfmt runs on every save.
writing_documentation
The way it works is very similar to Go. It's very simple: there's no need to write documentation for your code, vdoc will generate it from the source code.
Documentation for each function/type/const must be placed right before the declaration:
// clearall clears all bits in the array
fn clearall() {
}
An overview of the module must be placed in the first comment right after the module's name.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Advanced Topics
Calling C functions from V
#flag -lsqlite3
#include "sqlite3.h"
struct C.sqlite3
struct C.sqlite3_stmt
fn main() {
path := 'users.db'
db := &C.sqlite3{!} // a temporary hack meaning `sqlite3* db = 0`
C.sqlite3_open(path.str, &db)
query := 'select count(*) from users'
stmt := &C.sqlite3_stmt{!}
C.sqlite3_prepare_v2(db, query.str, - 1, &stmt, 0)
C.sqlite3_step(stmt)
nr_users := C.sqlite3_column_int(stmt, 0)
C.sqlite3_finalize(stmt)
println(nr_users)
}
Add #flag directives to the top of your V files to provide C compilation flags like -l for linking, -I for adding include files locations, -D for setting compile
time variables, etc.
You can use different flags for different targets. Right now, linux , darwin , and windows are supported.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
C strings can be converted to V strings with string(cstring) or string(cstring, len) .
V uses voidptr for C's void* and byteptr for C's byte* or char* .
To debug issues with the C code, v -show_c_cmd . is useful. It prints the C command that is used to build the program.
Compile time if
$if windows {
println('Windows')
}
$if linux {
println('Linux')
}
$if mac {
println('macOS')
}
$if debug {
println('debugging')
}
Compile time if starts with a $ . Right now it can only be used to detect an OS or a -debug compilation option.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
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:
Inline assembly
TODO: not implemented yet
fn main() {
a := 10
asm x64 {
mov eax, [a]
add eax, 10
mov [a], eax
}
}
Translating C/C++ to V
TODO: translating C to V will be available in V 0.3. C++ to V will be available later this year.
V can translate your C/C++ code to human readable V code. Let's create a simple program test.cpp first:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
#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;
}
When should you translate C code and when should you simply call C code from V?
If you have well-written, well-tested C code, then of course you can always simply call this C code from V.
- If you plan to develop that code base, you now have everything in one language, which is much safer and easier to develop in than C.
- Cross-compilation becomes a lot easier. You don't have to worry about it at all.
import time
import os
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
[live]
fn print_message() {
println('Hello! Modify this message while the program is running.')
}
fn main() {
for {
print_message()
time.sleep_ms(500)
}
}
Functions that you want to be reloaded must have [live] attribute before their definition.
Right now it's not possible to modify types while the program is running.
Cross compilation
To cross compile your project simply run
v -os windows .
or
v -os linux .
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 .
You will need to install Clang, LLD linker, and download a zip file with libraries and include files for Windows and Linux. V will provide you with a link.
V can be used as an alternative to Bash to write deployment scripts, build scripts, etc.
The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. "V scripts" run on Unix-like systems as well
as on Windows.
Start your program with a #v directive. It will make all functions in the os module global (so that you can use ls() instead of os.ls() , for example).
#v
rm('build/*')
// Same as:
for file in ls('build/') {
rm(file)
}
mv('*.v', 'build/')
// Same as:
for file in ls('.') {
if file.ends_with('.v') {
mv(file, 'build/')
}
}
Now you can either compile this like a normal V program and get an executable you can deploy and run anywhere: v deploy.v && ./deploy
Appendix I: Keywords
V has 23 keywords:
break
const
continue
defer
else
enum
fn
for
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
go
goto
if
import
in
interface
match
module
mut
none
or
pub
return
struct
type
Precedence Operator
5 * / % << >> &
4 + - | ^
3 == != < <= > >=
2 &&
1 ||
Assignment Operators
+= -= *= /= %=
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
&= |= ^=
>>= <<=
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD