Idioms
Filter a list
odd_numbers := [1, 2, 3, 4].filter(it % 2 == 1)
Check if array contains element
10 in [1, 2, 3, 4]
Check if a map does not contain a key
int_to_hex_string := {
1: '0x1'
2: '0x2'
}
10 !in int_to_hex_string
String interpolation
println('Hello, ${name}')
Sum types handling
type StringOrIntOrBool = bool | int | string
fn process(val StringOrIntOrBool) {
match val {
string { println('string') }
int { println('int') }
else { println('other') }
}
}
Iterate over a range
for i in 0 .. 10 {}
Iterate over an array
for index, element in arr {}
// or
for element in arr {}
Returning multiple values
fn foo() (int, int) {
return 2, 3
}
a, b := foo()
println(a)
println(b)
c, _ := foo() // ignore values using `_`
Return value or error
fn first(arr []int) !int {
if arr.len == 0 {
return error('array is empty')
}
return arr[0]
}
Error handling
fn get() !int { ... }
val := get() or {
println('Error: ${err}')
exit(1)
}
println(val)
If unwrapping
fn get() !int { ... }
if val := get() {
println(val)
} else {
println('Error: ${err}')
exit(1)
}
If expression
val := if a == 1 {
100
} else if a == 2 {
200
} else {
300
}
Swap two variables
a, b = b, a
Get CLI parameters
import os
println(os.args)
Generic function
fn sum[T](a T, b T) T {
return a + b
}
Embed file
embedded_file := $embed_file('index.html')
println(embedded_file.to_string())
Runtime reflection
module main
import v.reflection
fn main() {
a := 100
typ := reflection.type_of(a)
println(typ.name) // int
}
Compile-time reflection
struct User {
name string
age int
}
fn main() {
$for field in User.fields {
$if field.name == 'name' {
println('found name field')
}
}
}
Defer execution
fn main() {
mut f := os.open('log.txt') or { panic(err) }
defer {
f.close()
}
f.writeln('All ok')
}
Run function in separate thread
spawn foo()