2019-11-21 02:36:55 +01:00
# V Documentation
## Introduction
V is a statically typed compiled programming language designed for building maintainable software.
2020-08-16 19:16:59 +02:00
It's similar to Go and its design has also been influenced by Oberon, Rust, Swift,
Kotlin, and Python.
2019-11-21 02:36:55 +01:00
V is a very simple language. Going through this documentation will take you about half an hour,
2020-05-07 12:30:41 +02:00
and by the end of it you will have pretty much learned the entire language.
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
The language promotes writing simple and clear code with minimal abstraction.
2020-05-05 15:42:53 +02:00
2020-05-07 15:36:34 +02:00
Despite being simple, V gives the developer a lot of power. Anything you can do in other languages,
2019-11-21 02:36:55 +01:00
you can do in V.
2020-05-10 15:49:43 +02:00
## Table of Contents
2020-05-11 20:21:41 +02:00
2020-05-10 15:49:43 +02:00
< table >
2020-06-26 20:01:30 +02:00
< tr > < td width = 33% valign = top >
2020-06-26 20:00:52 +02:00
* [Hello world ](#hello-world )
* [Comments ](#comments )
* [Functions ](#functions )
2020-07-23 18:55:54 +02:00
* [Returning multiple values ](#returning-multiple-values )
2020-08-09 04:12:08 +02:00
* [Variable number of arguments ](#variable-number-of-arguments )
2020-07-23 18:55:54 +02:00
* [Symbol visibility ](#symbol-visibility )
2020-06-26 20:00:52 +02:00
* [Variables ](#variables )
* [Types ](#types )
* [Strings ](#strings )
2020-07-14 19:26:14 +02:00
* [Numbers ](#numbers )
2020-06-26 20:00:52 +02:00
* [Arrays ](#arrays )
* [Maps ](#maps )
2020-07-23 18:55:54 +02:00
* [Module imports ](#module-imports )
* [Statements & expressions ](#statements--expressions )
2020-06-26 20:00:52 +02:00
* [If ](#if )
2020-07-23 18:55:54 +02:00
* [In operator ](#in-operator )
2020-06-26 20:00:52 +02:00
* [For loop ](#for-loop )
* [Match ](#match )
* [Defer ](#defer )
* [Structs ](#structs )
2020-07-23 18:55:54 +02:00
* [Embedded structs ](#embedded-structs )
* [Default field values ](#default-field-values )
2020-07-23 00:37:37 +02:00
* [Short struct literal syntax ](#short-struct-initialization-syntax )
2020-06-26 20:00:52 +02:00
* [Access modifiers ](#access-modifiers )
* [Methods ](#methods )
2020-06-26 20:01:30 +02:00
< / td > < td width = 33% valign = top >
2020-06-26 20:00:52 +02:00
2020-08-24 11:45:40 +02:00
* [println and other builtin functions ](#println-and-other-builtin-functions )
2020-06-26 20:00:52 +02:00
* [Functions 2 ](#functions-2 )
* [Pure functions by default ](#pure-functions-by-default )
2020-06-30 14:29:55 +02:00
* [Mutable arguments ](#mutable-arguments )
2020-06-26 20:00:52 +02:00
* [Anonymous & high order functions ](#anonymous--high-order-functions )
* [References ](#references )
* [Modules ](#modules )
* [Constants ](#constants )
* [Types 2 ](#types-2 )
* [Interfaces ](#interfaces )
* [Enums ](#enums )
* [Sum types ](#sum-types )
* [Option/Result types & error handling ](#optionresult-types-and-error-handling )
* [Generics ](#generics )
* [Concurrency ](#concurrency )
* [Decoding JSON ](#decoding-json )
* [Testing ](#testing )
* [Memory management ](#memory-management )
* [ORM ](#orm )
2020-07-14 19:26:14 +02:00
< / td > < td valign = top >
2020-06-26 20:00:52 +02:00
* [Writing documentation ](#writing-documentation )
* [Tools ](#tools )
* [vfmt ](#vfmt )
* [Profiling ](#profiling )
* [Advanced ](#advanced )
2020-07-23 00:36:23 +02:00
* [Memory-unsafe code ](#memory-unsafe-code )
2020-06-26 20:00:52 +02:00
* [Calling C functions from V ](#calling-c-functions-from-v )
2020-07-14 19:24:59 +02:00
* [Debugging generated C code ](#debugging-generated-c-code )
2020-06-26 20:00:52 +02:00
* [Conditional compilation ](#conditional-compilation )
* [Compile time pseudo variables ](#compile-time-pseudo-variables )
2020-08-11 17:57:39 +02:00
* [Compile-time reflection ](#compile-time-reflection )
2020-06-26 20:00:52 +02:00
* [Limited operator overloading ](#limited-operator-overloading )
* [Inline assembly ](#inline-assembly )
* [Translating C/C++ to V ](#translating-cc-to-v )
* [Hot code reloading ](#hot-code-reloading )
* [Cross compilation ](#cross-compilation )
* [Cross-platform shell scripts in V ](#cross-platform-shell-scripts-in-v )
* [Attributes ](#attributes )
* [Appendices ](#appendices )
* [Keywords ](#appendix-i-keywords )
* [Operators ](#appendix-ii-operators )
2020-06-26 19:36:40 +02:00
2020-06-26 20:12:52 +02:00
< / td > < / tr >
2020-05-10 15:49:43 +02:00
< / table >
2020-05-11 20:21:41 +02:00
2020-05-05 15:42:53 +02:00
2019-11-21 02:36:55 +01:00
## Hello World
```v
fn main() {
println('hello world')
}
```
2020-05-31 07:42:34 +02:00
Save that snippet into a file `hello.v` . Now do: `v run hello.v` .
2019-11-21 02:36:55 +01:00
2020-07-09 17:14:14 +02:00
> That is assuming you have symlinked your V with `v symlink`, as described
2020-05-31 11:12:37 +02:00
[here ](https://github.com/vlang/v/blob/master/README.md#symlinking ).
If you have not yet, you have to type the path to V manually.
2020-05-31 07:42:34 +02:00
Congratulations - you just wrote your first V program, and executed it!
2020-05-31 11:12:37 +02:00
> You can compile a program without execution with `v hello.v`.
See `v help` for all supported commands.
2020-05-31 07:42:34 +02:00
In the above example, you can see that functions are declared with `fn` .
2020-07-09 17:14:14 +02:00
The return type goes after the function name. In this case `main` doesn't
2020-05-31 07:42:34 +02:00
return anything, so the return type can be omitted.
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
As in many other languages (such as C, Go and Rust), `main` is an entry point.
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
`println` is one of the few built-in functions. It prints the value passed to it
2019-11-21 02:36:55 +01:00
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
```v
println('hello world')
```
## Comments
```v
// This is a single line comment.
/* This is a multiline comment.
/* It can be nested. */
*/
```
## Functions
```v
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` .
2020-06-30 14:29:55 +02:00
This is true for all declarations in V and eliminates the need for header files
2019-11-21 02:36:55 +01:00
or thinking about the order of files and declarations.
2020-07-23 18:55:54 +02:00
### Returning multiple values
2020-04-16 02:01:55 +02:00
2019-11-21 02:36:55 +01:00
```v
fn foo() (int, int) {
return 2, 3
}
a, b := foo()
println(a) // 2
println(b) // 3
2020-07-14 19:24:59 +02:00
c, _ := foo() // ignore values using `_ `
2019-11-21 02:36:55 +01:00
```
2020-08-09 04:12:08 +02:00
### Variable number of arguments
```v
fn sum(a ...int) int {
mut total := 0
for x in a {
total += x
}
return total
}
println(sum()) // Output: 0
println(sum(1)) // 1
println(sum(2,3)) // 5
```
2020-07-23 18:55:54 +02:00
## Symbol visibility
2019-11-21 02:36:55 +01:00
```v
pub fn public_function() {
}
fn private_function() {
}
```
2020-07-23 18:55:54 +02:00
Functions are private (not exported) by default.
2020-05-11 20:21:41 +02:00
To allow other modules to use them, prepend `pub` . The same applies
to constants and types.
2020-05-11 20:25:48 +02:00
## Variables
2019-11-21 02:36:55 +01:00
```v
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.
2020-06-30 14:29:55 +02:00
To choose a different type, use type conversion:
2019-11-21 02:36:55 +01:00
the expression `T(v)` converts the value `v` to the
type `T` .
Unlike most other languages, V only allows defining variables in functions.
2020-07-23 18:55:54 +02:00
Global (module level) variables are not allowed. There's no global state in V
(see [Pure functions by default ](#pure-functions-by-default ) for details).
2019-11-21 02:36:55 +01:00
2020-07-23 18:55:54 +02:00
### Mutable variables
2020-05-11 20:25:48 +02:00
2019-11-21 02:36:55 +01:00
```v
2020-04-21 05:11:50 +02:00
mut age := 20
2019-11-21 02:36:55 +01:00
println(age)
age = 21
println(age)
```
To change the value of the variable use `=` . In V, variables are
2020-04-21 05:11:50 +02:00
immutable by default. To be able to change the value of the variable, you have to declare it with `mut` .
2019-11-21 02:36:55 +01:00
2020-04-21 05:11:50 +02:00
Try compiling the program above after removing `mut` from the first line.
2019-11-21 02:36:55 +01:00
2020-07-23 18:55:54 +02:00
### Initialization vs assignment
2020-09-07 13:50:12 +02:00
Note the (important) difference between `:=` and `=` .
2019-11-21 02:36:55 +01:00
`:=` is used for declaring and initializing, `=` is used for assigning.
```v
fn main() {
age = 21
}
```
2020-05-07 12:30:41 +02:00
This code will not compile, because the variable `age` is not declared.
2019-11-21 02:36:55 +01:00
All variables need to be declared in V.
```v
fn main() {
age := 21
}
```
2020-06-30 14:29:55 +02:00
### Declaration errors
2020-05-07 12:30:41 +02:00
In development mode the compiler will warn you that you haven't used the variable (you'll get an "unused variable" warning).
In production mode (enabled by passing the `-prod` flag to v – `v -prod foo.v` ) it will not compile at all (like in Go).
2019-11-21 02:36:55 +01:00
```v
fn main() {
a := 10
if true {
2020-07-23 18:55:54 +02:00
a := 20 // error: shadowed variable
2019-11-21 02:36:55 +01:00
}
2020-07-23 18:55:54 +02:00
// warning: unused variable `a`
2019-11-21 02:36:55 +01:00
}
```
2020-05-07 12:30:41 +02:00
Unlike most languages, variable shadowing is not allowed. Declaring a variable with a name that is already used in a parent scope will cause a compilation error.
2019-11-21 02:36:55 +01:00
2020-06-26 19:36:40 +02:00
## Types
### Primitive types
2019-11-21 02:36:55 +01:00
```v
bool
string
i8 i16 int i64 i128 (soon)
byte u16 u32 u64 u128 (soon)
rune // represents a Unicode code point
f32 f64
2020-05-27 05:42:48 +02:00
any_int, any_float // internal intermediate types of number literals
2020-06-11 07:00:14 +02:00
byteptr, voidptr, charptr, size_t // these are mostly used for C interoperability
2020-05-17 16:11:48 +02:00
any // similar to C's void* and Go's interface{}
2019-11-21 02:36:55 +01:00
```
Please note that unlike C and Go, `int` is always a 32 bit integer.
2020-05-27 05:42:48 +02:00
There is an exceptions to the rule that all operators
in V must have values of the same type on both sides. A small primitive type
on one side can be automatically promoted if it fits
2020-06-02 17:00:14 +02:00
completely into the data range of the type on the other side.
2020-05-27 05:42:48 +02:00
These are the allowed possibilities:
```
i8 → i16 → int → i64
2020-06-02 17:00:14 +02:00
↘ ↘
f32 → f64
↗ ↗
2020-05-27 05:42:48 +02:00
byte → u16 → u32 → u64 ⬎
↘ ↘ ↘ ptr
i8 → i16 → int → i64 ⬏
```
An `int` value for example can be automatically promoted to `f64`
2020-06-28 02:19:52 +02:00
or `i64` but not to `f32` or `u32` . (`f32` would mean precision
2020-05-27 05:42:48 +02:00
loss for large values and `u32` would mean loss of the sign for
negative values).
2020-06-26 19:36:40 +02:00
### Strings
2019-11-21 02:36:55 +01:00
```v
name := 'Bob'
println('Hello, $name!') // `$` is used for string interpolation
println(name.len)
bobby := name + 'by' // + is used to concatenate strings
println(bobby) // "Bobby"
println(bobby[1..3]) // "ob"
2020-04-21 05:11:50 +02:00
mut s := 'hello '
2019-11-21 02:36:55 +01:00
s += 'world' // `+=` is used to append to a string
println(s) // "hello world"
```
In V, a string is a read-only array of bytes. String data is encoded using UTF-8.
Strings are immutable.
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}'` .
2020-05-07 12:30:41 +02:00
Format specifiers similar to those in C's `printf()` are also supported. `f` , `g` , `x` , etc. are optional
2020-05-02 00:43:59 +02:00
and specify the output format. The compiler takes care of the storage size, so there is no `hd` or `llu` .
```v
2020-05-06 02:56:46 +02:00
println('x = ${x:12.3f}')
println('${item:-20} ${n:20d}')
2020-05-02 00:43:59 +02:00
```
2020-05-07 12:30:41 +02:00
All operators in V must have values of the same type on both sides. This code will not compile if `age` is not a string (for example if `age` were an `int` ):
2019-11-21 02:36:55 +01:00
```v
println('age = ' + age)
```
We have to either convert `age` to a `string` :
```v
println('age = ' + age.str())
```
or use string interpolation (preferred):
```v
println('age = $age')
```
To denote character literals, use `
```v
a := `a`
assert 'aloha!'[0] == `a`
```
For raw strings, prepend `r` . Raw strings are not escaped:
```v
s := r'hello\nworld'
println(s) // "hello\nworld"
```
2020-07-14 10:10:36 +02:00
### Numbers
```v
a := 123
```
2020-07-14 15:46:13 +02:00
2020-07-14 10:10:36 +02:00
This will assign the value of 123 to `a` . By default `a` will have the
2020-07-14 10:38:40 +02:00
type `int` .
2020-07-14 10:10:36 +02:00
2020-07-14 19:26:14 +02:00
You can also use hexadecimal, binary or octal notation for integer literals:
2020-07-14 15:46:13 +02:00
2020-07-14 10:10:36 +02:00
```v
a := 0x7B
2020-07-14 19:26:14 +02:00
b := 0b01111011
c := 0o173
2020-07-14 10:10:36 +02:00
```
2020-07-14 19:26:14 +02:00
All of these will be assigned the same value, 123. They will all have type
`int` , no matter what notation you used.
2020-07-14 10:10:36 +02:00
2020-07-14 15:46:13 +02:00
V also supports writing numbers with `_` as separator:
```v
num := 1_000_000 // same as 1000000
three := 0b0_11 // same as 0b11
float_num := 3_122.55 // same as 3122.55
hexa := 0xF_F // same as 255
oct := 0o17_3 // same as 0o173
```
2020-07-14 10:10:36 +02:00
If you want a different type of integer, you can use casting:
2020-07-14 15:46:13 +02:00
2020-07-14 10:10:36 +02:00
```v
a := i64(123)
b := byte(42)
c := i16(12345)
```
Assigning floating point numbers works the same way:
2020-07-14 15:46:13 +02:00
2020-07-14 10:10:36 +02:00
```v
f := 1.0
f1 := f64(3.14)
f2 := f32(3.14)
```
2020-08-12 19:14:13 +02:00
If you do not specify the type explicitly, by default float literals
2020-07-14 10:10:36 +02:00
will have the type of `f64` .
2020-06-26 19:36:40 +02:00
### Arrays
2019-11-21 02:36:55 +01:00
```v
2020-04-21 05:11:50 +02:00
mut nums := [1, 2, 3]
2019-11-21 02:36:55 +01:00
println(nums) // "[1, 2, 3]"
println(nums[1]) // "2"
2020-06-30 14:37:02 +02:00
nums[1] = 5
println(nums) // "[1, 5, 3]"
2019-11-21 02:36:55 +01:00
2020-06-30 14:37:02 +02:00
println(nums.len) // "3"
nums = [] // The array is now empty
println(nums.len) // "0"
// Declare an empty array:
users := []int{}
```
The type of an array is determined by the first element:
* `[1, 2, 3]` is an array of ints (`[]int`).
* `['a', 'b']` is an array of strings (`[]string`).
2020-07-26 20:29:51 +02:00
If V is unable to infer the type of an array, the user can explicitly specify it for the first element: `[byte(16), 32, 64, 128]` .
2020-06-30 14:37:02 +02:00
V arrays are homogeneous (all elements must have the same type). This means that code like `[1, 'a']` will not compile.
2020-07-26 20:29:51 +02:00
The `.len` field returns the length of the array. Note that it's a read-only field,
2020-06-30 14:37:02 +02:00
and it can't be modified by the user. Exported fields are read-only by default in V.
See [Access modifiers ](#access-modifiers ).
2020-07-26 20:29:51 +02:00
#### Array operations
2020-06-30 14:37:02 +02:00
```v
mut nums := [1, 2, 3]
2019-11-21 02:36:55 +01:00
nums < < 4
println(nums) // "[1, 2, 3, 4]"
2020-06-30 14:37:02 +02:00
// append array
2019-11-21 02:36:55 +01:00
nums < < [5, 6, 7]
println(nums) // "[1, 2, 3, 4, 5, 6, 7]"
2020-04-21 05:11:50 +02:00
mut names := ['John']
2019-11-21 02:36:55 +01:00
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"
```
`<<` is an operator that appends a value to the end of the array.
It can also append an entire array.
2020-06-30 14:37:02 +02:00
`val in array` returns true if the array contains `val` . See [`in` operator ](#in-operator ).
2019-11-21 02:36:55 +01:00
2020-07-26 20:29:51 +02:00
#### Initializing array properties
2020-07-07 11:55:22 +02:00
During initialization you can specify the capacity of the array (`cap`), its initial length (`len`),
2020-07-26 20:29:51 +02:00
and the default element (`init`):
```v
arr := []int{ len: 5, init: -1 } // `[-1, -1, -1, -1, -1]`
```
2020-07-07 11:55:22 +02:00
2020-07-26 20:29:51 +02:00
Setting the capacity improves performance of insertions, as it reduces the number of reallocations needed:
2020-07-07 11:55:22 +02:00
```v
2020-07-22 16:28:09 +02:00
mut numbers := []int{ cap: 1000 }
2020-07-26 20:29:51 +02:00
println(numbers.len) // 0
// Now appending elements won't reallocate
2020-07-07 11:55:22 +02:00
for i in 0 .. 1000 {
numbers < < i
}
```
2020-07-26 20:29:51 +02:00
Note: The above code uses a [range `for` ](#range-for ) statement.
2020-07-07 11:55:22 +02:00
2020-06-30 14:37:02 +02:00
#### Array methods
2019-11-21 02:36:55 +01:00
All arrays can be easily printed with `println(arr)` and converted to a string
with `s := arr.str()` .
2020-05-07 12:30:41 +02:00
Arrays can be efficiently filtered and mapped with the `.filter()` and
2019-11-21 02:36:55 +01:00
`.map()` methods:
```v
nums := [1, 2, 3, 4, 5, 6]
even := nums.filter(it % 2 == 0)
println(even) // [2, 4, 6]
words := ['hello', 'world']
upper := words.map(it.to_upper())
println(upper) // ['HELLO', 'WORLD']
```
2020-05-07 18:01:09 +02:00
`it` is a builtin variable which refers to element currently being processed in filter/map methods.
2019-11-21 02:36:55 +01:00
2020-08-05 01:46:04 +02:00
#### Multidimensional Arrays
Arrays can have more than one dimension.
2d array example:
```v
mut a := [][]int{len:2, init: []int{len:3}}
a[0][1] = 2
println(a) // [[0, 2, 0], [0, 0, 0]]
```
3d array example:
```v
mut a := [][][]int{len:2, init: [][]int{len:3, init: []int{len:2}}}
a[0][1][1] = 2
println(a) // [[[0, 0], [0, 2], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
```
2020-08-12 19:14:13 +02:00
#### Sorting arrays
Sorting arrays of all kinds is very simple and intuitive. Special variables `a` and `b`
are used when providing a custom sorting condition.
```v
mut numbers := [1, 3, 2]
numbers.sort() // 1, 2, 3
numbers.sort(a > b) // 3, 2, 1
```
```v
struct User { age int name string }
mut users := [...]
users.sort(a.age < b.age ) / / sort by User . age int field
users.sort(a.name > b.name) // reverse sort by User.name string field
```
2020-06-26 19:36:40 +02:00
### Maps
2019-11-21 02:36:55 +01:00
```v
2020-04-21 05:11:50 +02:00
mut m := map[string]int // Only maps with string keys are allowed for now
2019-11-21 02:36:55 +01:00
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')
2020-04-26 17:19:08 +02:00
// Short syntax
2019-11-21 02:36:55 +01:00
numbers := {
2020-06-26 13:07:57 +02:00
'one': 1
2020-01-16 15:29:00 +01:00
'two': 2
2019-11-21 02:36:55 +01:00
}
```
2020-07-23 18:55:54 +02:00
## Module imports
2020-07-18 21:34:38 +02:00
For information about creating a module, see [Modules ](#modules )
2020-07-23 18:55:54 +02:00
### Importing a module
2020-07-18 21:34:38 +02:00
Modules can be imported using keyword `import` .
2020-06-26 19:36:40 +02:00
```v
import os
fn main() {
name := os.input('Enter your name:')
println('Hello, $name!')
}
```
2020-07-18 21:34:38 +02:00
When using constants from other modules, the module name must be prefixed. However,
you can import functions and types from other modules directly:
```v
import os { input }
import crypto.sha256 { sum }
import time { Time }
```
2020-07-23 18:55:54 +02:00
### Module import aliasing
2020-07-18 21:34:38 +02:00
Any imported module name can be aliased using the `as` keyword:
NOTE: this example will not compile unless you have created `mymod/sha256.v`
```v
import crypto.sha256
import mymod.sha256 as mysha256
fn main() {
v_hash := sha256.sum('hi'.bytes()).hex()
my_hash := mysha256.sum('hi'.bytes()).hex()
assert my_hash == v_hash
}
```
You cannot alias an imported function or type.
However, you _can_ redeclare a type.
```v
import time
type MyTime time.Time
fn main() {
my_time := MyTime{
year: 2020,
month: 12,
day: 25
}
println(my_time.unix_time())
}
```
2020-06-26 19:36:40 +02:00
2020-07-23 18:55:54 +02:00
## Statements & expressions
2020-06-26 19:36:40 +02:00
### If
2019-11-21 02:36:55 +01:00
```v
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:
```v
num := 777
s := if num % 2 == 0 {
'even'
}
else {
'odd'
}
println(s) // "odd"
```
2020-07-09 17:14:14 +02:00
#### Is check
You can check sum types using `if` like `match` ing them.
```v
struct Abc {
val string
}
struct Xyz {
foo string
}
type Alphabet = Abc | Xyz
x := Alphabet(Abc{'test'}) // sum type
if x is Abc {
// x is automatically castet to Abc and can be used here
println(x)
}
```
If you have a struct field which should be checked, there is also a way to name a alias.
```
if x.bar is MyStruct as bar {
// x.bar cannot be castet automatically, instead you say "as bar" which creates a variable with the MyStruct typing
println(bar)
}
```
2020-06-26 19:36:40 +02:00
### In operator
2019-11-21 02:36:55 +01:00
`in` allows to check whether an array or a map contains an element.
```v
nums := [1, 2, 3]
println(1 in nums) // true
m := {'one': 1, 'two': 2}
println('one' in m) // true
```
2020-05-07 12:30:41 +02:00
It's also useful for writing clearer and more compact boolean expressions:
2019-11-21 02:36:55 +01:00
```v
if parser.token == .plus || parser.token == .minus ||
parser.token == .div || parser.token == .mult {
...
}
if parser.token in [.plus, .minus, .div, .mult] {
...
}
```
2020-05-07 12:30:41 +02:00
V optimizes such expressions, so both `if` statements above produce the same machine code and no arrays are created.
2019-11-21 02:36:55 +01:00
2020-06-26 19:36:40 +02:00
### For loop
2019-11-21 02:36:55 +01:00
2020-07-23 18:55:35 +02:00
V has only one looping keyword: `for` , with several forms.
#### Array `for`
2019-11-21 02:36:55 +01:00
```v
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
2020-07-23 18:55:35 +02:00
} // 1) Peter
2019-11-21 02:36:55 +01:00
```
2020-07-23 18:55:35 +02:00
The `for value in arr` form is used for going through elements of an array.
If an index is required, an alternative form `for index, value in arr` can be used.
2019-11-21 02:36:55 +01:00
Note, that the value is read-only. If you need to modify the array while looping, you have to use indexing:
```v
2020-06-30 14:29:55 +02:00
mut numbers := [0, 1, 2]
for i, _ in numbers {
numbers[i]++
2019-11-21 02:36:55 +01:00
}
2020-06-30 14:29:55 +02:00
println(numbers) // [1, 2, 3]
2019-11-21 02:36:55 +01:00
```
2020-06-30 14:29:55 +02:00
When an identifier is just a single underscore, it is ignored.
2019-11-21 02:36:55 +01:00
2020-07-31 18:08:12 +02:00
#### Map `for`
```v
m := {'one':1, 'two':2}
for key, value in m {
println("$key -> $value") // Output: one -> 1
} // two -> 2
```
Either key or value can be ignored by using a single underscore as the identifer.
```v
m := {'one':1, 'two':2}
// iterate over keys
for key, _ in m {
println(key) // Output: one
} // two
// iterate over values
for _, value in m {
println(value) // Output: 1
} // 2
```
2020-07-23 18:55:35 +02:00
#### Range `for`
```v
// Prints '01234'
for i in 0..5 {
print(i)
}
```
2020-08-12 19:14:13 +02:00
`low..high` means an *exclusive* range, which represents all values
2020-07-23 18:55:35 +02:00
from `low` up to *but not including* `high` .
#### Condition `for`
2019-11-21 02:36:55 +01:00
```v
2020-04-21 05:11:50 +02:00
mut sum := 0
mut i := 0
2019-11-21 02:36:55 +01:00
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.
2020-07-23 18:55:35 +02:00
#### Bare `for`
2019-11-21 02:36:55 +01:00
```v
2020-04-21 05:11:50 +02:00
mut num := 0
2019-11-21 02:36:55 +01:00
for {
2020-07-23 18:55:35 +02:00
num += 2
2019-11-21 02:36:55 +01:00
if num >= 10 {
break
}
}
println(num) // "10"
```
2020-05-07 12:30:41 +02:00
The condition can be omitted, resulting in an infinite loop.
2019-11-21 02:36:55 +01:00
2020-07-23 18:55:35 +02:00
#### C `for`
2019-11-21 02:36:55 +01:00
```v
2020-07-23 18:55:35 +02:00
for i := 0; i < 10 ; i + = 2 {
2019-11-21 02:36:55 +01:00
// Don't print 6
if i == 6 {
continue
}
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.
2020-04-21 05:11:50 +02:00
Here `i` doesn't need to be declared with `mut` since it's always going to be mutable by definition.
2019-11-21 02:36:55 +01:00
2020-06-26 19:36:40 +02:00
### Match
2019-11-21 02:36:55 +01:00
```v
os := 'windows'
print('V is running on ')
match os {
'darwin' { println('macOS.') }
'linux' { println('Linux.') }
else { println(os) }
}
2020-07-08 15:56:49 +02:00
```
A match statement is a shorter way to write a sequence of `if - else` statements.
When a matching branch is found, the following statement block will be run.
The else branch will be run when no other branches match.
2019-11-21 02:36:55 +01:00
2020-07-08 15:56:49 +02:00
```v
2020-01-16 15:29:00 +01:00
number := 2
2019-11-21 02:36:55 +01:00
s := match number {
1 { 'one' }
2 { 'two' }
2020-01-16 15:29:00 +01:00
else { 'many'}
2019-11-21 02:36:55 +01:00
}
```
2020-07-08 15:56:49 +02:00
A match expression returns the final expression from each branch.
2019-11-21 02:36:55 +01:00
```v
enum Color {
red
blue
green
}
fn is_red_or_blue(c Color) bool {
return match c {
2020-08-29 11:03:16 +02:00
.red, .blue { true } // comma can be used to test multiple values
2020-07-08 15:56:49 +02:00
.green { false }
2019-11-21 02:36:55 +01:00
}
}
```
A match statement can also be used to branch on the variants of an `enum`
2020-07-08 15:56:49 +02:00
by using the shorthand `.variant_here` syntax. An `else` branch is not allowed
when all the branches are exhaustive.
2019-11-21 02:36:55 +01:00
2020-07-22 02:31:32 +02:00
```v
c := `v`
typ := match c {
`0` ...`9` { 'digit' }
`A` ...`Z` { 'uppercase' }
`a` ...`z` { 'lowercase' }
else { 'other' }
}
println(typ) // 'lowercase'
```
You can also use ranges as `match` patterns. If the value falls within the range
of a branch, that branch will be executed.
Note that the ranges use `...` (three dots) rather than `..` (two dots). This is
because the range is *inclusive* of the last element, rather than exclusive
(as `..` ranges are). Using `..` in a match branch will throw an error.
2020-06-26 19:36:40 +02:00
### Defer
A defer statement defers the execution of a block of statements until the surrounding function returns.
```v
fn read_log() {
2020-09-12 07:31:15 +02:00
f := os.open('log.txt') or { panic(err) }
2020-06-26 19:36:40 +02:00
defer { f.close() }
...
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
}
```
2019-11-21 02:36:55 +01:00
## Structs
```v
struct Point {
x int
y int
}
2020-07-08 16:02:35 +02:00
mut p := Point{
2019-11-21 02:36:55 +01:00
x: 10
y: 20
}
2020-01-16 15:29:00 +01:00
2019-11-21 02:36:55 +01:00
println(p.x) // Struct fields are accessed using a dot
2020-07-08 16:02:35 +02:00
// Alternative literal syntax for structs with 3 fields or fewer
p = Point{10, 20}
assert p.x == 10
2019-11-21 02:36:55 +01:00
```
2020-07-23 18:55:54 +02:00
### Heap structs
2020-05-16 15:19:48 +02:00
2019-11-21 02:36:55 +01:00
Structs are allocated on the stack. To allocate a struct on the heap
and get a reference to it, use the `&` prefix:
```v
p := & Point{10, 10}
// References have the same syntax for accessing fields
println(p.x)
```
2020-07-23 18:55:54 +02:00
The type of `p` is `&Point` . It's a [reference ](#references ) to `Point` .
2019-11-21 02:36:55 +01:00
References are similar to Go pointers and C++ references.
2020-07-23 18:55:54 +02:00
### Embedded structs
2020-05-16 15:17:27 +02:00
2020-05-16 15:19:48 +02:00
V doesn't allow subclassing, but it supports embedded structs:
2019-11-21 02:36:55 +01:00
```v
// TODO: this will be implemented later
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)
```
2020-07-23 18:55:54 +02:00
### Default field values
2020-05-16 15:19:48 +02:00
2020-05-16 15:17:27 +02:00
```v
struct Foo {
2020-05-17 16:01:02 +02:00
n int // n is 0 by default
s string // s is '' by default
a []int // a is `[]int{}` by default
2020-05-16 15:19:48 +02:00
pos int = -1 // custom default value
2020-05-16 15:17:27 +02:00
}
```
2020-05-16 15:19:48 +02:00
2020-05-17 19:24:04 +02:00
All struct fields are zeroed by default during the creation of the struct. Array and map fields are allocated.
2020-05-17 16:01:02 +02:00
It's also possible to define custom default values.
2020-05-16 15:17:27 +02:00
2020-05-17 16:11:48 +02:00
2020-07-08 16:02:35 +02:00
< a id = 'short-struct-initialization-syntax' / >
2020-05-17 16:11:48 +02:00
2020-07-23 00:37:37 +02:00
### Short struct literal syntax
```v
mut p := Point{x: 10, y: 20}
// you can omit the struct name when it's already known
p = {x: 30, y: 4}
assert p.y == 4
```
Omitting the struct name also works for returning a struct literal or passing one
as a function argument.
#### Trailing struct literal arguments
V doesn't have default function arguments or named arguments, for that trailing struct
literal syntax can be used instead:
2020-05-17 16:11:48 +02:00
```v
struct ButtonConfig {
text string
is_disabled bool
width int = 70
height int = 20
}
2020-05-17 16:15:02 +02:00
2020-05-17 16:11:48 +02:00
fn new_button(c ButtonConfig) & Button {
return & Button{
width: c.width
height: c.height
text: c.text
}
}
2020-07-08 16:02:35 +02:00
button := new_button(text:'Click me', width:100)
// the height is unset, so it's the default value
assert button.height == 20
2020-05-17 16:11:48 +02:00
```
2020-07-23 00:37:37 +02:00
As you can see, both the struct name and braces can be omitted, instead of:
2020-05-17 16:15:02 +02:00
```
new_button(ButtonConfig{text:'Click me', width:100})
```
2020-07-23 00:37:37 +02:00
This only works for functions that take a struct for the last argument.
2020-05-17 16:15:02 +02:00
2020-06-26 19:36:40 +02:00
### Access modifiers
2019-11-21 02:36:55 +01:00
Struct fields are private and immutable by default (making structs immutable as well).
Their access modifiers can be changed with
2020-04-21 05:11:50 +02:00
`pub` and `mut` . In total, there are 5 possible options:
2019-11-21 02:36:55 +01:00
```v
struct Foo {
a int // private immutable (default)
2020-04-23 19:05:27 +02:00
mut:
2019-11-21 02:36:55 +01:00
b int // private mutable
c int // (you can list multiple fields with the same access modifier)
pub:
2020-06-28 02:19:52 +02:00
d int // public immutable (readonly)
2020-04-23 19:05:27 +02:00
pub mut:
2019-11-21 02:36:55 +01:00
e int // public, but mutable only in parent module
__global:
f int // public and mutable both inside and outside parent module
} // (not recommended to use, that's why the 'global' keyword
// starts with __ )
```
For example, here's the `string` type defined in the `builtin` module:
```v
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.
2020-05-07 12:30:41 +02:00
The `len` field is public, but immutable:
2019-11-21 02:36:55 +01:00
```v
fn main() {
str := 'hello'
len := str.len // OK
str.len++ // Compilation error
}
```
2020-05-16 15:36:19 +02:00
This means that defining public readonly fields is very easy in V, no need in getters/setters or properties.
2020-06-26 19:36:40 +02:00
### Methods
2019-11-21 02:36:55 +01:00
```v
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"
```
2020-07-23 18:55:54 +02:00
V doesn't have classes, but you can define methods on types.
2019-11-21 02:36:55 +01:00
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.
2020-06-26 19:36:40 +02:00
## Functions 2
### Pure functions by default
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
V functions are pure by default, meaning that their return values are a function of their arguments only,
2020-07-23 18:55:54 +02:00
and their evaluation has no side effects (besides I/O).
2019-11-21 02:36:55 +01:00
2020-06-30 14:29:55 +02:00
This is achieved by a lack of global variables and all function arguments being immutable by default,
even when [references ](#references ) are passed.
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
V is not a purely functional language however.
2020-06-30 14:29:55 +02:00
There is a compiler flag to enable global variables (`--enable-globals`), but this is
intended for low-level applications like kernels and drivers.
### Mutable arguments
2020-05-07 12:30:41 +02:00
It is possible to modify function arguments by using the keyword `mut` :
2019-11-21 02:36:55 +01:00
```v
struct User {
2020-04-23 19:05:27 +02:00
mut:
2019-11-21 02:36:55 +01:00
is_registered bool
}
2020-04-21 05:11:50 +02:00
fn (mut u User) register() {
2019-11-21 02:36:55 +01:00
u.is_registered = true
}
2020-04-21 05:11:50 +02:00
mut user := User{}
2019-11-21 02:36:55 +01:00
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:
```v
2020-04-21 05:11:50 +02:00
fn multiply_by_2(mut arr []int) {
2020-02-24 17:55:16 +01:00
for i in 0..arr.len {
2019-11-21 02:36:55 +01:00
arr[i] *= 2
}
}
2020-04-21 05:11:50 +02:00
mut nums := [1, 2, 3]
multiply_by_2(mut nums)
2019-11-21 02:36:55 +01:00
println(nums) // "[2, 4, 6]"
```
2020-04-21 05:11:50 +02:00
Note, that you have to add `mut` before `nums` when calling this function. This makes
2019-11-21 02:36:55 +01:00
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.
2020-06-30 14:29:55 +02:00
For this reason V doesn't allow the modification of arguments with primitive types such as integers. Only more complex types such as arrays and maps may be modified.
2019-11-21 02:36:55 +01:00
Use `user.register()` or `user = register(user)`
2020-04-21 05:11:50 +02:00
instead of `register(mut user)` .
2019-11-21 02:36:55 +01:00
V makes it easy to return a modified version of an object:
```v
fn register(u User) User {
return { u | is_registered: true }
}
user = register(user)
```
2020-06-26 19:36:40 +02:00
### Anonymous & high order functions
2019-11-21 02:36:55 +01:00
```v
fn sqr(n int) int {
return n * n
}
fn run(value int, op fn(int) int) int {
return op(value)
}
fn main() {
println(run(5, sqr)) // "25"
2020-05-07 15:36:34 +02:00
2020-04-22 07:23:05 +02:00
// Anonymous functions can be declared inside other functions:
double_fn := fn(n int) int {
return n + n
}
println(run(5, double_fn)) // "10"
2020-05-07 15:36:34 +02:00
2020-04-22 07:23:05 +02:00
// Functions can be passed around without assigning them to variables:
res := run(5, fn(n int) int {
return n + n
})
2019-11-21 02:36:55 +01:00
}
```
## References
```v
fn (foo Foo) bar_method() {
...
}
fn bar_function(foo Foo) {
...
}
```
2020-05-07 12:30:41 +02:00
If a function argument is immutable (like `foo` in the examples above)
V can pass it either value or reference. The compiler will determine this by itself,
and the developer doesn't need to think about it.
2019-11-21 02:36:55 +01:00
You no longer need to remember whether you should pass the struct by value
or by reference.
2020-05-07 12:30:41 +02:00
You can ensure that the struct is always passed by reference by
2019-11-21 02:36:55 +01:00
adding `&` :
```v
fn (foo & Foo) bar() {
println(foo.abc)
}
```
`foo` is still immutable and can't be changed. For that,
2020-04-21 05:11:50 +02:00
`(mut foo Foo)` has to be used.
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
In general, V's references are similar to Go pointers and C++ references.
2019-11-21 02:36:55 +01:00
For example, a tree structure definition would look like this:
```v
struct Node< T > {
val T
left & Node
right & Node
}
```
## Constants
```v
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 values can never be changed.
V constants are more flexible than in most languages. You can assign more complex values:
```v
struct Color {
r int
g int
b int
}
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}
2020-06-30 14:29:55 +02:00
// evaluate function call at compile-time
2019-11-21 02:36:55 +01:00
blue = rgb(0, 0, 255)
)
println(numbers)
println(red)
println(blue)
```
Global variables are not allowed, so this can be really useful.
2020-05-21 16:34:57 +02:00
<!--
2019-11-21 02:36:55 +01:00
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:
2020-05-21 16:34:57 +02:00
-->
2019-11-21 02:36:55 +01:00
```v
println('Top cities: $TOP_CITIES.filter(.usa)')
vs
println('Top cities: $top_cities.filter(.usa)')
```
2020-08-24 11:45:40 +02:00
## println and other builtin functions
2019-11-21 02:36:55 +01:00
`println` is a simple yet powerful builtin function. It can print anything:
strings, numbers, arrays, maps, structs.
```v
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
2020-06-30 14:29:55 +02:00
`.str() string` method:
```v
struct Color {
r int
g int
b int
}
pub fn (c Color) str() string { return '{$c.r, $c.g, $c.b}' }
red := Color{r: 255, g: 0, b: 0}
println(red)
```
2019-11-21 02:36:55 +01:00
If you don't want to print a newline, use `print()` instead.
2020-08-24 11:45:40 +02:00
The number of builtin functions is low. Other builtin functions are:
```
fn exit(exit_code int)
fn panic(message string)
fn print_backtrace()
```
2019-11-21 02:36:55 +01:00
## 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:
```v
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.
That's it, you can now use it in your code:
```v
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.
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:
```v
2020-07-11 21:20:28 +02:00
fn init() {
2019-11-21 02:36:55 +01:00
// your setup code here ...
}
```
The init function cannot be public. It will be called automatically.
2020-06-26 19:36:40 +02:00
## Types 2
### Interfaces
2019-11-21 02:36:55 +01:00
```v
struct Dog {}
struct Cat {}
fn (d Dog) speak() string {
return 'woof'
}
fn (c Cat) speak() string {
return 'meow'
}
interface Speaker {
speak() string
}
2019-11-30 09:18:06 +01:00
fn perform(s Speaker) string {
2020-05-14 17:50:48 +02:00
if s is Dog { // use `is` to check the underlying type of an interface
println('perform(dog)')
2020-08-24 11:14:35 +02:00
println(s.breed) // `s` is automatically cast to `Dog` (smart cast)
2020-05-14 17:50:48 +02:00
} else if s is Cat {
println('perform(cat)')
}
2019-11-30 09:18:06 +01:00
return s.speak()
2019-11-21 02:36:55 +01:00
}
dog := Dog{}
cat := Cat{}
2019-11-30 09:18:06 +01:00
println(perform(dog)) // "woof"
println(perform(cat)) // "meow"
2019-11-21 02:36:55 +01:00
```
A type implements an interface by implementing its methods.
There is no explicit declaration of intent, no "implements" keyword.
2020-06-26 19:36:40 +02:00
### Enums
2019-11-21 02:36:55 +01:00
```v
enum Color {
red green blue
}
2020-04-21 05:11:50 +02:00
mut color := Color.red
2019-11-21 02:36:55 +01:00
// V knows that `color` is a `Color` . No need to use `color = Color.green` here.
color = .green
2020-08-24 11:14:35 +02:00
println(color) // "green"
match color {
.red { ... }
.green { ... }
.blue { ... }
}
2019-11-21 02:36:55 +01:00
```
2020-08-24 11:14:35 +02:00
Enum match must be exhaustive or have an `else` branch. This ensures that if a new enum field is added, it's handled everywhere in the code.
2020-06-26 19:36:40 +02:00
### Sum types
2020-05-05 15:42:53 +02:00
2020-07-06 18:09:38 +02:00
A sum type instance can hold a value of several different types. Use the `type`
keyword to declare a sum type:
2020-05-05 15:42:53 +02:00
2020-07-06 18:09:38 +02:00
```v
struct Moon {}
struct Mars {}
struct Venus {}
2020-05-05 15:42:53 +02:00
2020-07-06 18:09:38 +02:00
type World = Moon | Mars | Venus
2020-05-05 15:42:53 +02:00
2020-07-06 18:09:38 +02:00
sum := World(Moon{})
2020-05-05 15:42:53 +02:00
```
2020-07-06 18:09:38 +02:00
To check whether a sum type instance holds a certain type, use `sum is Type` .
2020-07-14 19:24:59 +02:00
To cast a sum type to one of its variants you can use `sum as Type` :
2020-05-05 15:42:53 +02:00
```v
2020-07-06 18:09:38 +02:00
fn (m Mars) dust_storm() bool
fn main() {
mut w := World(Moon{})
assert w is Moon
w = Mars{}
// use `as` to access the Mars instance
mars := w as Mars
if mars.dust_storm() {
println('bad weather!')
}
}
2020-05-05 15:42:53 +02:00
```
2020-07-14 19:24:59 +02:00
### Matching sum types
2020-07-06 18:09:38 +02:00
You can also use `match` to determine the variant:
2020-06-18 17:37:41 +02:00
```v
2020-07-06 18:09:38 +02:00
fn open_parachutes(n int)
fn land(w World) {
match w {
Moon {} // no atmosphere
Mars {
// light atmosphere
open_parachutes(3)
}
Venus {
// heavy atmosphere
open_parachutes(1)
}
}
}
2020-06-18 17:37:41 +02:00
```
2020-07-06 18:09:38 +02:00
`match` must have a pattern for each variant or have an `else` branch.
There are 2 ways to access the cast variant inside a match branch:
2020-06-18 17:37:41 +02:00
- the shadowed match variable
- using `as` to specify a variable name
```v
2020-07-06 18:09:38 +02:00
fn (m Moon) moon_walk()
fn (m Mars) shiver()
fn (v Venus) sweat()
fn pass_time(w World) {
match w {
2020-08-24 11:14:35 +02:00
// using the shadowed match variable, in this case `w` (smart cast)
2020-07-06 18:09:38 +02:00
Moon { w.moon_walk() }
Mars { w.shiver() }
else {}
}
2020-07-08 15:56:49 +02:00
// using `as` to specify a name for each value
match w as var {
Mars { var.shiver() }
Venus { var.sweat() }
2020-07-06 18:09:38 +02:00
else {
// w is of type World
2020-07-08 15:56:49 +02:00
assert w is Moon
2020-07-06 18:09:38 +02:00
}
}
}
2020-06-18 17:37:41 +02:00
```
2020-06-18 17:52:21 +02:00
Note: shadowing only works when the match expression is a variable. It will not work on struct fields, arrays indexing, or map key lookup.
2020-06-26 19:36:40 +02:00
### Option/Result types and error handling
2019-11-21 02:36:55 +01:00
2020-07-14 19:24:59 +02:00
Option types are declared with `?Type` :
2019-11-21 02:36:55 +01:00
```v
struct User {
id int
name string
}
struct 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')
}
fn main() {
2020-07-14 19:24:59 +02:00
repo := Repo {
users: [User{1, 'Andrew'}, User {2, 'Bob'}, User {10, 'Charles'}]
}
2020-07-12 19:27:41 +02:00
user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks
return
2019-11-21 02:36:55 +01:00
}
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.
2020-05-07 18:01:09 +02:00
The amount of work required to "upgrade" a function to an optional function is minimal;
2019-11-21 02:36:55 +01:00
you have to add a `?` to the return type and return an error when something goes wrong.
2020-05-07 18:01:09 +02:00
If you don't need to return an error message, you can simply `return none` (this is a more efficient equivalent of `return error("")` ).
2019-11-21 02:36:55 +01:00
2020-05-07 18:01:09 +02:00
This is the primary mechanism for error handling in V. They are still values, like in Go,
2019-11-21 02:36:55 +01:00
but the advantage is that errors can't be unhandled, and handling them is a lot less verbose.
2020-07-11 10:26:22 +02:00
Unlike other languages, V does not handle exceptions with `throw/try/catch` blocks.
2019-11-21 02:36:55 +01:00
`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.
```v
user := repo.find_user_by_id(7) or {
println(err) // "User 7 not found"
return
}
```
2020-07-14 19:24:59 +02:00
### Handling optionals
2020-07-12 19:27:41 +02:00
2020-07-15 21:57:41 +02:00
There are four ways of handling an optional. The first method is to
2020-07-14 19:24:59 +02:00
propagate the error:
2019-11-21 02:36:55 +01:00
```v
2020-07-14 19:24:59 +02:00
import net.http
fn f(url string) ?string {
2020-08-29 01:56:43 +02:00
resp := http.get(url) ?
2020-07-14 19:24:59 +02:00
return resp.text
}
2019-11-21 02:36:55 +01:00
```
2020-08-12 19:14:13 +02:00
`http.get` returns `?http.Response` . Because `?` follows the call, the
error will be propagated to the caller of `f` . When using `?` after a
function call producing an optional, the enclosing function must return
an optional as well. If error propagation is used in the `main()`
function it will `panic` instead, since the error cannot be propagated
2020-07-14 19:24:59 +02:00
any further.
2020-05-07 18:01:09 +02:00
2020-07-14 19:24:59 +02:00
The body of `f` is essentially a condensed version of:
2019-11-21 02:36:55 +01:00
```v
2020-07-14 19:24:59 +02:00
resp := http.get(url) or {
return error(err)
}
return resp.text
2019-11-21 02:36:55 +01:00
```
2020-07-14 19:24:59 +02:00
---
The second method is to break from execution early:
2020-07-12 19:27:41 +02:00
```v
user := repo.find_user_by_id(7) or {
return
}
```
Here, you can either call `panic()` or `exit()` , which will stop the execution of the entire program,
or use a control flow statement (`return`, `break` , `continue` , etc) to break from the current block.
Note that `break` and `continue` can only be used inside a `for` loop.
2020-07-15 21:57:41 +02:00
V does not have a way to forcibly "unwrap" an optional (as other languages do, for instance Rust's `unwrap()`
or Swift's `!` ). To do this, use `or { panic(err) }` instead.
2020-07-14 19:24:59 +02:00
---
2020-07-12 19:27:41 +02:00
The third method is to provide a default value at the end of the `or` block. In case of an error,
2020-07-14 19:24:59 +02:00
that value would be assigned instead, so it must have the same type as the content of the `Option` being handled.
2020-07-12 19:27:41 +02:00
```v
fn do_something(s string) ?string {
if s == 'foo' { return 'foo' }
return error('invalid string') // Could be `return none` as well
}
a := do_something('foo') or { 'default' } // a will be 'foo'
b := do_something('bar') or { 'default' } // b will be 'default'
```
2020-07-15 21:57:41 +02:00
---
The fourth method is to use `if` unwrapping:
```v
if resp := http.get(url) {
println(resp.text) // resp is a http.Response, not an optional
} else {
println(err)
}
```
2020-08-12 19:14:13 +02:00
Above, `http.get` returns a `?http.Response` . `resp` is only in scope for the first
2020-07-15 21:57:41 +02:00
`if` branch. `err` is only in scope for the `else` branch.
2020-04-23 05:35:33 +02:00
2019-11-21 02:36:55 +01:00
## Generics
```v
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)?
```
2020-08-01 15:34:23 +02:00
Another example:
```v
fn compare< T > (a, b T) int {
if a < b {
return -1
}
if a > b {
return 1
}
return 0
}
println(compare< int > (1,0)) // Outputs: 1
println(compare< int > (1,1)) // 0
println(compare< int > (1,2)) // -1
println(compare< string > ('1','0')) // Outputs: 1
println(compare< string > ('1','1')) // 0
println(compare< string > ('1','2')) // -1
2020-08-12 19:14:13 +02:00
println(compare< float > (1.1, 1.0)) // Outputs: 1
2020-08-01 15:34:23 +02:00
println(compare< float > (1.1, 1.1)) // 0
println(compare< float > (1.1, 1.2)) // -1
```
2019-11-21 02:36:55 +01:00
## Concurrency
2020-05-07 12:30:41 +02:00
V's model of concurrency is very similar to Go's. To run `foo()` concurrently, just
call it with `go foo()` . Right now, it launches the function on a new system
thread. Soon coroutines and a scheduler will be implemented.
2019-11-21 02:36:55 +01:00
2020-08-01 23:08:57 +02:00
```v
import sync
import time
fn task(id, duration int, mut wg sync.WaitGroup) {
println("task ${id} begin")
time.sleep_ms(duration)
println("task ${id} end")
wg.done()
}
fn main() {
mut wg := sync.new_waitgroup()
wg.add(3)
go task(1, 500, mut wg)
go task(2, 900, mut wg)
go task(3, 100, mut wg)
wg.wait()
println('done')
}
// Output: task 1 begin
// task 2 begin
// task 3 begin
// task 3 end
// task 1 end
// task 2 end
// done
```
2020-06-26 23:55:34 +02:00
Unlike Go, V has no channels (yet). Nevertheless, data can be exchanged between a coroutine
and the calling thread via a shared variable. This variable should be created as reference and passed to
the coroutine as `mut` . The underlying `struct` should also contain a `mutex` to lock concurrent access:
```v
import sync
struct St {
mut:
x int // share data
mtx & sync.Mutex
}
fn (mut b St) g() {
...
2020-07-04 12:44:25 +02:00
b.mtx.m_lock()
2020-06-26 23:55:34 +02:00
// read/modify/write b.x
...
b.mtx.unlock()
...
}
fn caller() {
mut a := & St{ // create as reference so it's on the heap
x: 10
mtx: sync.new_mutex()
}
go a.g()
...
2020-07-04 12:44:25 +02:00
a.mtx.m_lock()
2020-06-26 23:55:34 +02:00
// read/modify/write a.x
...
a.mtx.unlock()
...
}
```
2019-11-21 02:36:55 +01:00
## Decoding JSON
```v
import json
struct User {
name string
age int
// Use the `skip` attribute to skip certain fields
foo Foo [skip]
// If the field name is different in JSON, it can be specified
last_name string [json:lastName]
}
data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25 }'
user := json.decode(User, data) or {
eprintln('Failed to decode json')
return
}
println(user.name)
println(user.last_name)
println(user.age)
```
2020-05-07 18:01:09 +02:00
Because of the ubiquitous nature of JSON, support for it is built directly into V.
2019-11-21 02:36:55 +01:00
2020-05-07 18:01:09 +02:00
The `json.decode` function takes two arguments: the first argument of the `json.decode` function is the type into which the JSON value should be decoded and the second is a string containing the JSON data.
2019-11-21 02:36:55 +01:00
V generates code for JSON encoding and decoding. No runtime reflection is used. This results in much better
performance.
## Testing
```v
// hello.v
fn hello() string {
return 'Hello world'
}
// hello_test.v
fn test_hello() {
assert hello() == 'Hello world'
}
```
2020-05-07 12:30:41 +02:00
The `assert` keyword can be used outside of tests as well.
2020-02-08 17:00:35 +01:00
2020-05-07 12:30:41 +02:00
All test functions have to be placed in files named `<some name>_test.v` and test function names must begin with `test_` .
2019-11-21 02:36:55 +01:00
2020-04-06 17:11:01 +02:00
You can also define a special test function: `testsuite_begin` , which will be
2020-02-21 12:24:13 +01:00
run *before* all other test functions in a `_test.v` file.
2020-04-06 17:11:01 +02:00
You can also define a special test function: `testsuite_end` , which will be
2020-02-21 12:24:13 +01:00
run *after* all other test functions in a `_test.v` file.
2020-02-08 17:00:35 +01:00
To run the tests do `v hello_test.v` .
2019-11-21 02:36:55 +01:00
2020-02-08 17:00:35 +01:00
To test an entire module, do `v test mymodule` .
2020-06-28 02:19:52 +02:00
You can also do `v test .` to test everything inside your current folder (and subdirectories).
2020-02-08 17:00:35 +01:00
You can pass `-stats` to v test, to see more details about the individual tests in each _test.v file.
2019-11-21 02:36:55 +01:00
## Memory management
(Work in progress)
2020-05-07 12:30:41 +02:00
V doesn't use garbage collection or reference counting. The compiler cleans everything up
2019-11-21 02:36:55 +01:00
during compilation. If your V program compiles, it's guaranteed that it's going
to be leak free. For example:
```v
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.
```v
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
}
```
## ORM
2020-07-23 00:35:42 +02:00
(This is still in an alpha state)
2019-11-21 02:36:55 +01:00
2020-06-21 16:12:16 +02:00
V has a built-in ORM (object-relational mapping) which supports SQLite, and will soon support MySQL, Postgres, MS SQL, and Oracle.
2019-11-21 02:36:55 +01:00
2020-05-07 18:01:09 +02:00
V's ORM provides a number of benefits:
2019-11-21 02:36:55 +01:00
2020-07-23 00:35:42 +02:00
- One syntax for all SQL dialects. (Migrating between databases becomes much easier.)
- Queries are constructed using V's syntax. (There's no need to learn another syntax.)
- Safety. (All queries are automatically sanitised to prevent SQL injection.)
- Compile time checks. (This prevents typos which can only be caught during runtime.)
- Readability and simplicity. (You don't need to manually parse the results of a query and then manually construct objects from the parsed results.)
2019-11-21 02:36:55 +01:00
```v
2020-05-07 12:30:41 +02:00
struct Customer { // struct name has to be the same as the table name (for now)
2020-07-23 00:35:42 +02:00
id int // a field named `id` of integer type must be the first field
2019-11-21 02:36:55 +01:00
name string
nr_orders int
country string
}
2020-06-21 16:09:35 +02:00
db := sqlite.connect('customers.db')
2019-11-21 02:36:55 +01:00
// select count(*) from Customer
2020-06-21 16:09:35 +02:00
nr_customers := sql db { select count from Customer }
2019-11-21 02:36:55 +01:00
println('number of all customers: $nr_customers')
// V syntax can be used to build queries
// db.select returns an array
2020-06-21 16:09:35 +02:00
uk_customers := sql db { select from Customer where country == 'uk' & & nr_orders > 0 }
2019-11-21 02:36:55 +01:00
println(uk_customers.len)
for customer in uk_customers {
println('$customer.id - $customer.name')
}
// by adding `limit 1` we tell V that there will be only one object
2020-06-21 16:09:35 +02:00
customer := sql db { select from Customer where id == 1 limit 1 }
2019-11-21 02:36:55 +01:00
println('$customer.id - $customer.name')
// insert a new customer
new_customer := Customer{name: 'Bob', nr_orders: 10}
2020-06-21 16:09:35 +02:00
sql db { insert new_customer into Customer }
2019-11-21 02:36:55 +01:00
```
2020-06-21 16:12:16 +02:00
For more examples, see < a href = 'https://github.com/vlang/v/blob/master/vlib/orm/orm_test.v' > vlib/orm/orm_test.v< / a > .
2020-05-01 10:04:00 +02:00
## Writing Documentation
2019-11-21 02:36:55 +01:00
The way it works is very similar to Go. It's very simple: there's no need to
2020-08-30 08:55:53 +02:00
write documentation separately for your code, vdoc will generate it from docstrings in the source code.
2019-11-21 02:36:55 +01:00
Documentation for each function/type/const must be placed right before the declaration:
```v
// clearall clears all bits in the array
fn clearall() {
}
```
The comment must start with the name of the definition.
An overview of the module must be placed in the first comment right after the module's name.
2020-05-01 10:55:48 +02:00
To generate documentation use vdoc, for example `v doc net.http` .
2020-05-01 10:04:00 +02:00
2020-06-26 19:36:40 +02:00
## Tools
2020-07-17 13:03:07 +02:00
### v fmt
2020-06-26 19:36:40 +02:00
You don't need to worry about formatting your code or setting style guidelines.
2020-07-17 13:03:07 +02:00
`v fmt` takes care of that:
2020-06-26 19:36:40 +02:00
```v
v fmt file.v
```
2020-07-17 13:03:07 +02:00
It's recommended to set up your editor, so that `v fmt -w` runs on every save.
2020-06-26 19:36:40 +02:00
A vfmt run is usually pretty cheap (takes < 30ms ) .
Always run `v fmt -w file.v` before pushing your code.
### Profiling
2020-05-01 10:04:00 +02:00
V has good support for profiling your programs: `v -profile profile.txt run file.v`
That will produce a profile.txt file, which you can then analyze.
The generated profile.txt file will have lines with 4 columns:
a) how many times a function was called
b) how much time in total a function took (in ms)
c) how much time on average, a call to a function took (in ns)
d) the name of the v function
You can sort on column 3 (average time per function) using:
`sort -n -k3 profile.txt|tail`
2020-05-07 12:30:41 +02:00
You can also use stopwatches to measure just portions of your code explicitly:
2020-05-01 10:04:00 +02:00
```v
import time
fn main(){
2020-05-30 09:20:54 +02:00
sw := time.new_stopwatch({})
2020-05-01 10:04:00 +02:00
println('Hello world')
println('Greeting the world took: ${sw.elapsed().nanoseconds()}ns')
}
```
2019-11-21 02:36:55 +01:00
2020-02-09 09:32:36 +01:00
# Advanced Topics
2019-11-21 02:36:55 +01:00
2020-07-23 00:36:23 +02:00
## Memory-unsafe code
Sometimes for efficiency you may want to write low-level code that can potentially
2020-08-12 19:14:13 +02:00
corrupt memory or be vulnerable to security exploits. V supports writing such code,
2020-07-23 00:36:23 +02:00
but not by default.
V requires that any potentially memory-unsafe operations are marked intentionally.
Marking them also indicates to anyone reading the code that there could be
memory-safety violations if there was a mistake.
Examples of potentially memory-unsafe operations are:
* Pointer arithmetic
* Pointer indexing
* Conversion to pointer from an incompatible type
* Calling certain C functions, e.g. `free` , `strlen` and `strncmp` .
To mark potentially memory-unsafe operations, enclose them in an `unsafe` block:
```v
// allocate 2 uninitialized bytes & return a reference to them
2020-07-29 21:41:47 +02:00
mut p := unsafe { & byte(malloc(2)) }
2020-07-23 00:36:23 +02:00
p[0] = `h` // Error: pointer indexing is only allowed in `unsafe` blocks
unsafe {
2020-07-29 21:41:47 +02:00
p[0] = `h`
2020-07-23 00:36:23 +02:00
p[1] = `i`
}
p++ // Error: pointer arithmetic is only allowed in `unsafe` blocks
unsafe {
p++ // OK
}
assert *p == `i`
```
2020-07-29 21:41:47 +02:00
Best practice is to avoid putting memory-safe expressions inside an `unsafe` block,
2020-08-12 19:14:13 +02:00
so that the reason for using `unsafe` is as clear as possible. Generally any code
you think is memory-safe should not be inside an `unsafe` block, so the compiler
2020-07-29 21:41:47 +02:00
can verify it.
2020-07-23 00:36:23 +02:00
2020-08-12 19:14:13 +02:00
If you suspect your program does violate memory-safety, you have a head start on
finding the cause: look at the `unsafe` blocks (and how they interact with
2020-07-23 00:36:23 +02:00
surrounding code).
* Note: This is work in progress.
2019-11-21 02:36:55 +01:00
## Calling C functions from V
```v
#flag -lsqlite3
#include "sqlite3.h"
2020-07-11 09:49:42 +02:00
// See also the example from https://www.sqlite.org/quickstart.html
struct C.sqlite3{}
struct C.sqlite3_stmt{}
type FnSqlite3Callback fn(voidptr, int, & charptr, & charptr) int
fn C.sqlite3_open(charptr, & & C.sqlite3) int
fn C.sqlite3_close(& C.sqlite3) int
fn C.sqlite3_column_int(stmt & C.sqlite3_stmt, n int) int
// ... you can also just define the type of parameter & leave out the C. prefix
fn C.sqlite3_prepare_v2(& sqlite3, charptr, int, & & sqlite3_stmt, & charptr) int
fn C.sqlite3_step(& sqlite3_stmt)
fn C.sqlite3_finalize(& sqlite3_stmt)
fn C.sqlite3_exec(db & sqlite3, sql charptr, FnSqlite3Callback, cb_arg voidptr, emsg & charptr) int
fn C.sqlite3_free(voidptr)
fn my_callback(arg voidptr, howmany int, cvalues & charptr, cnames & charptr) int {
for i in 0..howmany {
print('| ${cstring_to_vstring(cnames[i])}: ${cstring_to_vstring(cvalues[i]):20} ')
}
println('|')
return 0
}
2019-11-21 02:36:55 +01:00
fn main() {
2020-07-23 22:49:56 +02:00
db := & C.sqlite3(0) // this means `sqlite3* db = 0`
C.sqlite3_open('users.db', & db) // passing a string literal to a C function call results in a C string, not a V string
// C.sqlite3_open(db_path.str, & db) // you can also use `.str byteptr` field to convert a V string to a C char pointer
2019-11-21 02:36:55 +01:00
query := 'select count(*) from users'
2020-02-08 17:00:35 +01:00
stmt := & C.sqlite3_stmt(0)
2019-11-21 02:36:55 +01:00
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)
2020-07-11 09:49:42 +02:00
println('There are $nr_users users in the database.')
//
error_msg := charptr(0)
query_all_users := 'select * from users'
rc := C.sqlite3_exec(db, query_all_users.str, my_callback, 7, & error_msg)
if rc != C.SQLITE_OK {
eprintln( cstring_to_vstring(error_msg) )
C.sqlite3_free(error_msg)
}
C.sqlite3_close(db)
2019-11-21 02:36:55 +01:00
}
```
2020-07-14 19:24:59 +02:00
### #flag
2020-02-08 17:00:35 +01:00
Add `#flag` directives to the top of your V files to provide C compilation flags like:
2019-11-21 02:36:55 +01:00
2020-02-08 17:00:35 +01:00
- `-I` for adding C include files search paths
- `-l` for adding C library names that you want to get linked
- `-L` for adding C library files search paths
- `-D` for setting compile time variables
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
You can use different flags for different targets. Currently the `linux` , `darwin` , `freebsd` , and `windows` flags are supported.
2020-02-08 17:00:35 +01:00
2020-05-07 12:30:41 +02:00
NB: Each flag must go on its own line (for now)
2019-11-21 02:36:55 +01:00
```v
#flag linux -lsdl2
#flag linux -Ivig
#flag linux -DCIMGUI_DEFINE_ENUMS_AND_STRUCTS=1
#flag linux -DIMGUI_DISABLE_OBSOLETE_FUNCTIONS=1
#flag linux -DIMGUI_IMPL_API=
```
2020-07-14 19:24:59 +02:00
### Including C code
2020-05-07 12:30:41 +02:00
You can also include C code directly in your V module. For example, let's say that your C code is located in a folder named 'c' inside your module folder. Then:
2020-02-08 17:00:35 +01:00
2020-02-29 14:23:45 +01:00
* Put a v.mod file inside the toplevel folder of your module (if you
2020-06-14 20:20:26 +02:00
created your module with `v new` you already have v.mod file). For
2020-02-29 14:23:45 +01:00
example:
2020-02-08 17:00:35 +01:00
```v
2020-02-29 14:23:45 +01:00
Module {
name: 'mymodule',
description: 'My nice module wraps a simple C library.',
version: '0.0.1'
dependencies: []
}
```
2020-03-01 15:49:39 +01:00
2020-02-29 14:23:45 +01:00
* Add these lines to the top of your module:
```v
#flag -I @VROOT/c
#flag @VROOT/c/implementation.o
2020-02-08 17:00:35 +01:00
#include "header.h"
```
2020-02-29 14:23:45 +01:00
NB: @VROOT will be replaced by V with the *nearest parent folder, where there is a v.mod file* .
2020-07-14 19:24:59 +02:00
Any .v file beside or below the folder where the v.mod file is, can use `#flag @VROOT/abc` to refer to this folder.
2020-04-06 17:11:01 +02:00
The @VROOT folder is also *prepended* to the module lookup path, so you can *import* other
2020-03-01 15:49:39 +01:00
modules under your @VROOT , by just naming them.
2020-02-08 17:00:35 +01:00
2020-07-14 19:24:59 +02:00
The instructions above will make V look for an compiled .o file in your module `folder/c/implementation.o` .
2020-02-08 17:00:35 +01:00
If V finds it, the .o file will get linked to the main executable, that used the module.
2020-02-29 14:23:45 +01:00
If it does not find it, V assumes that there is a `@VROOT/c/implementation.c` file,
2020-02-08 17:00:35 +01:00
and tries to compile it to a .o file, then will use that.
2020-02-29 14:23:45 +01:00
2020-02-08 17:00:35 +01:00
This allows you to have C code, that is contained in a V module, so that its distribution is easier.
2020-07-14 19:24:59 +02:00
You can see a complete minimal example for using C code in a V wrapper module here:
[project_with_c_code ](https://github.com/vlang/v/tree/master/vlib/v/tests/project_with_c_code ).
2020-02-08 17:00:35 +01:00
You can use `-cflags` to pass custom flags to the backend C compiler. You can also use `-cc` to change the default C backend compiler.
For example: `-cc gcc-9 -cflags -fsanitize=thread` .
2019-11-21 02:36:55 +01:00
2020-07-14 19:24:59 +02:00
### C types
2020-02-08 17:00:35 +01:00
Ordinary zero terminated C strings can be converted to V strings with `string(cstring)` or `string(cstring, len)` .
2019-11-21 02:36:55 +01:00
2020-07-14 19:24:59 +02:00
NB: Each `string(...)` function does NOT create a copy of the `cstring` , so you should NOT free it after calling `string()` . If you need to make a copy of the C string (some libc APIs like `getenv` pretty much require that, since they
return pointers to internal libc memory), you can use `cstring_to_vstring(cstring)` .
2020-02-08 17:00:35 +01:00
On Windows, C APIs often return so called `wide` strings (utf16 encoding).
These can be converted to V strings with `string_from_wide(&u16(cwidestring))` .
V has these types for easier interoperability with C:
- `voidptr` for C's `void*` ,
- `byteptr` for C's `byte*` and
- `charptr` for C's `char*` .
- `&charptr` for C's `char**`
2020-05-07 12:30:41 +02:00
To cast a `voidptr` to a V reference, use `user := &User(user_void_ptr)` .
2019-11-21 02:36:55 +01:00
2020-05-07 12:30:41 +02:00
`voidptr` can also be dereferenced into a V struct through casting: `user := User(user_void_ptr)` .
2019-11-21 02:36:55 +01:00
2020-07-14 19:24:59 +02:00
[socket.v has an example which calls C code from V ](https://github.com/vlang/v/blob/master/vlib/net/socket.v ) .
## Debugging generated C code
2020-02-08 17:00:35 +01:00
2020-05-07 12:30:41 +02:00
To debug issues in the generated C code, you can pass these flags:
2020-02-08 17:00:35 +01:00
- `-cg` - produces a less optimized executable with more debug information in it.
2020-05-02 18:01:43 +02:00
- `-showcc` - prints the C command that is used to build the program.
2019-11-21 02:36:55 +01:00
2020-07-06 12:42:11 +02:00
For the best debugging experience, you can pass all of them at the same time: `v -cg -showcc yourprogram.v` , then just run your debugger (gdb/lldb) or IDE on the produced executable `yourprogram` .
2020-02-08 17:00:35 +01:00
2020-05-07 12:30:41 +02:00
If you just want to inspect the generated C code, without further compilation, you can also use the `-o` flag (e.g. `-o file.c` ). This will make V produce the `file.c` then stop.
2019-11-21 02:36:55 +01:00
2020-05-02 18:01:43 +02:00
If you want to see the generated C source code for *just* a single C function, for example `main` , you can use: `-printfn main -o file.c` .
To see a detailed list of all flags that V supports, use `v help` , `v help build` , `v help build-c` .
2020-05-07 12:30:41 +02:00
## Conditional compilation
2019-11-21 02:36:55 +01:00
```v
$if windows {
println('Windows')
}
$if linux {
println('Linux')
}
2020-01-09 11:12:35 +01:00
$if macos {
2019-11-21 02:36:55 +01:00
println('macOS')
}
2020-08-20 08:33:08 +02:00
$else {
println('different OS')
}
2019-11-21 02:36:55 +01:00
$if debug {
println('debugging')
}
```
2020-05-07 12:30:41 +02:00
If you want an `if` to be evaluated at compile time it must be prefixed with a `$` sign. Right now it can only be used to detect
2019-11-21 02:36:55 +01:00
an OS or a `-debug` compilation option.
2020-05-26 22:39:15 +02:00
## Compile time pseudo variables
V also gives your code access to a set of pseudo string variables, that are substituted at compile time:
- `@FN` => replaced with the name of the current V function
- `@MOD` => replaced with the name of the current V module
- `@STRUCT` => replaced with the name of the current V struct
- `@FILE` => replaced with the path of the V source file
- `@LINE` => replaced with the V line number where it appears (as a string).
- `@COLUMN` => replaced with the column where it appears (as a string).
- `@VEXE` => replaced with the path to the V compiler
- `@VHASH` => replaced with the shortened commit hash of the V compiler (as a string).
- `@VMOD_FILE` => replaced with the contents of the nearest v.mod file (as a string).
That allows you to do the following example, useful while debugging/logging/tracing your code:
```v
eprintln( 'file: ' + @FILE + ' | line: ' + @LINE + ' | fn: ' + @MOD + '.' + @FN )
```
Another example, is if you want to embed the version/name from v.mod *inside* your executable:
```v
import v.vmod
vm := vmod.decode( @VMOD_FILE ) or { panic(err) }
eprintln('$vm.name $vm.version\n $vm.description')
```
2020-06-09 16:36:18 +02:00
## Performance tuning
2020-07-09 17:14:14 +02:00
The generated C code is usually fast enough, when you compile your code
with `-prod` . There are some situations though, where you may want to give
2020-08-24 09:04:50 +02:00
additional hints to the compiler, so that it can further optimize some
2020-06-09 18:09:41 +02:00
blocks of code.
NB: These are *rarely* needed, and should not be used, unless you
*profile your code*, and then see that there are significant benefits for them.
To cite gcc's documentation: "programmers are notoriously bad at predicting
how their programs actually perform".
`[inline]` - you can tag functions with `[inline]` , so the C compiler will
2020-07-09 17:14:14 +02:00
try to inline them, which in some cases, may be beneficial for performance,
2020-06-09 18:09:41 +02:00
but may impact the size of your executable.
2020-06-09 16:36:18 +02:00
2020-08-24 09:04:50 +02:00
`[direct_array_access]` - in functions tagged with `[direct_array_access]`
the compiler will translate array operations directly into C array operations -
omiting bounds checking. This may save a lot of time in a function that iterates
over an array but at the cost of making the function unsafe - unless
the boundries will be checked by the user.
2020-07-09 17:14:14 +02:00
`if _likely_(bool expression) {` this hints the C compiler, that the passed
boolean expression is very likely to be true, so it can generate assembly
2020-06-09 16:36:18 +02:00
code, with less chance of branch misprediction. In the JS backend,
that does nothing.
2020-06-09 17:08:31 +02:00
`if _unlikely_(bool expression) {` similar to `_likely_(x)` , but it hints that
the boolean expression is highly improbable. In the JS backend, that does nothing.
2020-08-11 17:57:39 +02:00
< a id = 'Reflection via codegen' >
## Compile-time reflection
2019-11-21 02:36:55 +01:00
Having built-in JSON support is nice, but V also allows you to create efficient
2020-08-11 17:57:39 +02:00
serializers for any data format. V has compile-time `if` and `for` constructs:
2019-11-21 02:36:55 +01:00
```v
// TODO: not implemented yet
2020-08-11 17:57:39 +02:00
struct User {
name string
age int
}
// Note: T should be passed a struct name only
2019-11-21 02:36:55 +01:00
fn decode< T > (data string) T {
2020-04-21 05:11:50 +02:00
mut result := T{}
2020-08-11 17:57:39 +02:00
// compile-time `for` loop
// T.fields gives an array of a field metadata type
$for field in T.fields {
$if field.Type is string {
// $(string_expr) produces an identifier
result.$(field.name) = get_string(data, field.name)
} else $if field.Type is int {
result.$(field.name) = get_int(data, field.name)
2019-11-21 02:36:55 +01:00
}
}
return result
}
2020-08-11 17:57:39 +02:00
// `decode<User>` generates:
2019-11-21 02:36:55 +01:00
fn decode_User(data string) User {
2020-04-21 05:11:50 +02:00
mut result := User{}
2019-11-21 02:36:55 +01:00
result.name = get_string(data, 'name')
result.age = get_int(data, 'age')
return result
}
```
## Limited operator overloading
```v
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
2020-05-07 12:30:41 +02:00
scientific and graphical applications are among V's domains, operator overloading is an important feature to have
2019-11-21 02:36:55 +01:00
in order to improve readability:
`a.add(b).add(c.mul(d))` is a lot less readable than `a + b + c * d` .
2020-05-07 12:30:41 +02:00
To improve safety and maintainability, operator overloading is limited:
2019-11-21 02:36:55 +01:00
2020-06-27 19:26:21 +02:00
- It's only possible to overload `+, -, *, /, %` operators.
2020-02-08 17:00:35 +01:00
- Calling other functions inside operator functions is not allowed.
- Operator functions can't modify their arguments.
- Both arguments must have the same type (just like with all operators in V).
2019-11-21 02:36:55 +01:00
## Inline assembly
TODO: not implemented yet
```v
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:
2020-06-29 17:59:31 +02:00
```cpp
2019-11-21 02:36:55 +01:00
#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` :
```v
fn main {
2020-07-11 15:37:55 +02:00
mut s := []string{}
2019-11-21 02:36:55 +01:00
s < < 'V is '
s < < 'awesome'
println(s.len)
}
```
An online C/C++ to V translator is coming soon.
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.
Translating it to V gives you several advantages:
2020-01-16 15:29:00 +01:00
- 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.
- No more build flags and include files either.
2019-11-21 02:36:55 +01:00
## Hot code reloading
```v
module main
import time
import os
[live]
fn print_message() {
println('Hello! Modify this message while the program is running.')
}
fn main() {
for {
print_message()
time.sleep_ms(500)
}
}
```
Build this example with `v -live message.v` .
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.
More examples, including a graphical application:
2020-02-17 12:19:15 +01:00
[github.com/vlang/v/tree/master/examples/hot_code_reload ](https://github.com/vlang/v/tree/master/examples/hot_reload ).
2019-11-21 02:36:55 +01:00
## Cross compilation
To cross compile your project simply run
```v
v -os windows .
```
or
```v
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` .
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.
## Cross-platform shell scripts in V
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.
2020-03-10 14:23:55 +01:00
Use the `.vsh` file extension. It will make all functions in the `os`
2019-11-21 02:36:55 +01:00
module global (so that you can use `ls()` instead of `os.ls()` , for example).
```v
2020-03-10 14:23:55 +01:00
#!/usr/local/bin/v run
// The shebang above associates the file to V on Unix-like systems,
// so it can be run just by specifying the path to the file
// once it's made executable using `chmod +x` .
2019-11-21 02:36:55 +01:00
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:
2020-03-10 14:23:55 +01:00
`v deploy.vsh && ./deploy`
Or just run it more like a traditional Bash script:
`v run deploy.vsh`
2019-11-21 02:36:55 +01:00
2020-03-10 14:23:55 +01:00
On Unix-like platforms, the file can be run directly after making it executable using `chmod +x` :
`./deploy.vsh`
2019-11-21 02:36:55 +01:00
2020-06-09 22:40:36 +02:00
## Attributes
2020-06-09 22:49:40 +02:00
V has several attributes that modify the behavior of functions and structs.
2020-08-10 02:00:14 +02:00
An attribute is specified inside `[]` right before a function/struct declaration and applies only to the following declaration.
2020-06-09 23:04:46 +02:00
2020-06-09 22:40:36 +02:00
```v
2020-06-09 22:47:41 +02:00
// Calling this function will result in a deprecation warning
2020-06-09 22:40:36 +02:00
[deprecated]
2020-06-09 22:49:40 +02:00
fn old_function() {}
// This function's calls will be inlined.
[inline]
fn inlined_function() {}
2020-06-09 22:40:36 +02:00
2020-06-09 22:47:41 +02:00
// The following struct can only be used as a reference (`& Window`) and allocated on the heap.
[ref_only]
2020-06-09 22:40:36 +02:00
struct Window {
}
// V will not generate this function and all its calls if the provided flag is false.
// To use a flag, use `v -d flag`
[if debug]
fn foo() { }
fn bar() {
foo() // will not be called if `-d debug` is not passed
}
2020-06-09 22:47:41 +02:00
// For C interop only, tells V that the following struct is defined with `typedef struct` in C
2020-07-09 17:14:14 +02:00
[typedef]
2020-06-09 22:47:41 +02:00
struct C.Foo { }
2020-07-10 13:14:08 +02:00
// Used in Win32 API code when you need to pass callback function
2020-06-09 22:40:36 +02:00
[windows_stdcall]
2020-07-10 13:14:08 +02:00
fn C.DefWindowProc(hwnd int, msg int, lparam int, wparam int)
2020-06-09 22:40:36 +02:00
```
2020-06-26 19:36:40 +02:00
# Appendices
2019-11-21 02:36:55 +01:00
## Appendix I: Keywords
2020-07-08 08:50:32 +02:00
V has 29 keywords (3 are literals):
2019-11-21 02:36:55 +01:00
```v
2020-06-29 17:59:31 +02:00
as
2020-07-08 08:50:32 +02:00
assert
2019-11-21 02:36:55 +01:00
break
const
continue
defer
else
enum
2020-07-08 08:50:32 +02:00
false
2019-11-21 02:36:55 +01:00
fn
for
go
goto
if
import
in
interface
2020-06-29 17:59:31 +02:00
is
2019-11-21 02:36:55 +01:00
match
module
2020-07-07 16:57:39 +02:00
mut
2019-11-21 02:36:55 +01:00
none
or
pub
return
struct
2020-07-08 08:50:32 +02:00
true
2019-11-21 02:36:55 +01:00
type
2020-07-08 08:50:32 +02:00
unsafe
2019-11-21 02:36:55 +01:00
```
2020-07-08 08:50:32 +02:00
See also [Types ](#types ).
2019-11-21 02:36:55 +01:00
## Appendix II: Operators
2020-07-23 18:55:54 +02:00
This lists operators for [primitive types ](#primitive-types ) only.
2019-11-21 02:36:55 +01:00
```v
+ sum integers, floats, strings
- difference integers, floats
* product integers, floats
/ quotient integers, floats
% remainder integers
& bitwise AND integers
| bitwise OR integers
^ bitwise XOR integers
< < left shift integer < < unsigned integer
>> right shift integer >> unsigned integer
Precedence Operator
5 * / % < < >> &
4 + - | ^
3 == != < < = > >=
2 & &
1 ||
Assignment Operators
+= -= *= /= %=
& = |= ^=
>>= < < =
```