V Types

Primitive types

bool string i8 i16 int i64 i128 u8 u16 u32 u64 u128 rune // represents a Unicode code point f32 f64 isize, usize // platform-dependent, the size is how many bytes it takes to reference any location in memory voidptr // this one is mostly used for [C interoperability](#v-and-c)

[!NOTE] int is a platform-width signed integer: 64 bits on 64-bit targets and 32 bits on 32-bit targets. Use i32 or i64 when you need a fixed width. Integer literal casts to int are checked against the target platform's width.

128-bit integers

i128 and u128 hold 128 bits. The usual operators work on them: arithmetic, bitwise, shifts, comparisons, and casts to and from the other numeric types.

fn main() { total := u128(1) << 100 // 2^100 assert total / u128(4) == u128(1) << 98 assert (u128(1) << 127) * u128(2) == u128(0) // wraps at 128 bits assert i128(-8) >> 1 == i128(-4) // keeps the sign assert i128(-8) >>> 1 == (u128(1) << 127) - u128(4) }

A shift by 128 or more gives 0. The count is read at its own width, so a count that does not fit in 64 bits shifts everything out rather than being taken for a small one. >> on a negative signed value is an arithmetic shift, so it gives -1 once the value is all ones, while >>> reads the same bits as unsigned and its result is a u128, whatever the sign of the operand. Division or modulo by zero panics, as it does for the other integer types, and overflow wraps.

The compiler does not require a 128-bit C type. Every operation becomes a call to a small helper, and the helper has two implementations: the C compiler's own __int128 where it exists (gcc, clang), and one built from 64-bit limbs everywhere else (tcc, MSVC, every 32-bit target), where a 128-bit value is a struct. Both answer identically, down to the rounding of a cast to f64: the whole 128-bit magnitude is rounded once, rather than each limb on its own. Pass -d v3_no_native_int128 to force the portable implementation on a compiler that has the native type.

Managed arrays of wide integers and structs containing them retain 16-byte element alignment on both 32-bit and 64-bit targets, including after growth or cloning.

Printing works through str(), so println and string interpolation show the decimal value, including the minimum i128 that has no positive counterpart.

A literal that needs more than 64 bits can be written directly and keeps its exact value:

fn main() { assert u128(31732946804115296442105984367).str() == '31732946804115296442105984367' }

The digits are split into two halves in the compiler, so the C compiler never sees a constant it would quietly cut down to its low 64 bits. A value outside the range of the target type is an error: u128(2^128) is rejected rather than wrapped, and i128(-2^127) is allowed because that is the minimum. Negative literals keep their full magnitude before negation, including values below the i64 minimum: i128(-9223372036854775809) is exactly -9223372036854775809.

A bare literal still follows the rule that applies to every other integer in V, so it wants an explicit cast.

The promotion ladder has a row for both new types, so wide + u64(1) is a u128 and keeps all 128 bits, and asking the expression for its own type answers u128 too. A narrower operand widens by its own sign, so i128(0) + u64(0xffffffffffffffff) is 2^64 - 1 rather than -1.

The usual conversions are there, so text, hex and binary work on a 128-bit value:

fn main() { wide := u128(1) << 100 assert '12345'.u128() == u128(12345) assert wide.hex() == '10000000000000000000000000' assert wide.bin().len == 101 }

Format specifiers work on a 128-bit value, and a map of them prints its values:

fn main() { wide := (u128(1) << 100) + u128(255) assert '${wide:08x}' == '100000000000000000000000ff' m := { 'a': wide } assert m.str().contains('100000000000000000000000ff') }

str_base covers the bases a specifier cannot spell out: wide.str_base(2) writes the value in binary, and char_str writes the code point in the low bits.

typeof and a method called on a mixed-width expression name the wider operand: typeof(x + u64(1)) is u128, and (x + u64(1)).str() keeps all of its digits. Only json and json2 still have no encoder for either type.

There is an exception 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 completely into the data range of the type on the other side. These are the allowed possibilities:

i8 → i16 → int → i64 ↘ ↘ f32 → f64 ↗ ↗ u8 → u16 → u32 → u64 ⬎ ↘ ↘ ↘ ptr i8 → i16 → int → i64 ⬏

An int value for example can be automatically promoted to f64 or i64 but not to u32. (u32 would mean loss of the sign for negative values). Promotion from int to f32, however, is currently done automatically (but can lead to precision loss for large values).

Literals like 123 or 4.56 are treated in a special way. They do not lead to type promotions, however they default to int and f64 respectively, when their type has to be decided:

u := u16(12) v := 13 + u // v is of type `u16` - no promotion x := f32(45.6) y := x + 3.14 // y is of type `f32` - no promotion a := 75 // a is of type `int` - default for int literal b := 14.7 // b is of type `f64` - default for float literal c := u + a // c is of type `int` - automatic promotion of `u`'s value d := b + x // d is of type `f64` - automatic promotion of `x`'s value

Strings

In V, strings are encoded in UTF-8, and are immutable (read-only) by default:

s := 'hello 🌎' // the `world` emoji takes 4 bytes, and string length is reported in bytes assert s.len == 10 arr := s.bytes() // convert `string` to `[]u8` assert arr.len == 10 s2 := arr.bytestr() // convert `[]u8` to `string` assert s2 == s name := 'Bob' assert name.len == 3 // indexing gives a byte, u8(66) == `B` assert name[0] == u8(66) // slicing gives a string 'ob' assert name[1..3] == 'ob' // escape codes // escape special characters like in C windows_newline := '\r\n' assert windows_newline.len == 2 // arbitrary bytes can be directly specified using `\x##` notation where `#` is // a hex digit aardvark_str := '\x61ardvark' assert aardvark_str == 'aardvark' assert '\xc0'[0] == u8(0xc0) // or using octal escape `\###` notation where `#` is an octal digit aardvark_str2 := '\141ardvark' assert aardvark_str2 == 'aardvark' // Unicode can be specified directly as `\u####` where # is a hex digit // and will be converted internally to its UTF-8 representation star_str := '\u2605' // ★ assert star_str == '★' // UTF-8 can be specified this way too, as individual bytes. assert star_str == '\xe2\x98\x85'

Since strings are immutable, you cannot directly change characters in a string:

mut s := 'hello 🌎' s[0] = `H` // not allowed

error: cannot assign to s[i] since V strings are immutable

Note that indexing a string normally will produce a u8 (byte), not a rune nor another string. Indexes correspond to bytes in the string, not Unicode code points. If you want to convert the u8 to a string, use the .ascii_str() method on the u8:

country := 'Netherlands' println(country[0]) // Output: 78 println(country[0].ascii_str()) // Output: N

However, you can easily get the runes for a string with the runes() method, which will return an array of the UTF-8 characters from the string. You can then index this array. Just be aware that there may be fewer indexes available on the rune array than on the bytes in the string, if there are any non-ASCII characters.

mut s := 'hello 🌎' // there are 10 bytes in the string (as shown earlier), but only 7 runes, since the `world` emoji // only counts as one `rune` (one Unicode character) assert s.runes().len == 7 println(s.runes()[6])

If you want the code point from a specific string index or other more advanced UTF-8 processing and conversions, refer to the vlib/encoding/utf8 module.

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.

Prepend r for raw strings. Escapes are not handled, so you will get exactly what you type:

s := r'hello\nworld' // the `\n` will be preserved as two characters println(s) // "hello\nworld"

Strings can be easily converted to integers:

s := '42' n := s.int() // 42 // all int literals are supported assert '0xc3'.int() == 195 assert '0o10'.int() == 8 assert '0b1111_0000_1010'.int() == 3850 assert '-0b1111_0000_1010'.int() == -3850

For more advanced string processing and conversions, refer to the vlib/strconv module.

String interpolation

Basic interpolation syntax is pretty simple - use ${ before a variable name and } after. The variable will be converted to a string and embedded into the literal:

name := 'Bob' println('Hello, ${name}!') // Hello, Bob!

It also works with fields: 'age = ${user.age}'. You may also use more complex expressions: 'can register = ${user.age > 13}'.

Format specifiers similar to those in C's printf() are also supported. f, g, x, o, b, etc. are optional and specify the output format. The compiler takes care of the storage size, so there is no hd or llu.

To use a format specifier, follow this pattern:

${varname:[flags][width][.precision][type]}

  • flags: may be zero or more of the following: - to left-align output within the field, 0 to use 0 as the padding character instead of the default space character, and + to show the sign of decimal integers and floats with a width or precision. The + flag may be combined with - and 0 in any order; left alignment uses trailing spaces even when 0 is also present.

    Note

    V does not currently support the use of ' or # as format flags.

  • width: may be an integer value describing the minimum width of total field to output. For runtime widths, wrap an int expression in parentheses, for example ${name:(width)}.

  • precision: an integer value preceded by a . will guarantee that many digits after the decimal point without any insignificant trailing zeros. If displaying insignificant zero's is desired, append a f specifier to the precision value (see examples below). Applies only to float variables and is ignored for integer variables. Runtime precisions use the same parenthesized form, for example ${value:(width).(precision)f}. Negative zero keeps its sign when formatted, including when trailing zeros are omitted.

  • type: f and F specify the input is a float and should be rendered as such, e and E specify the input is a float and should be rendered as an exponent (partially broken), g and G specify the input is a float--the renderer will use floating point notation for small values and exponent notation for large values, d specifies the input is an integer and should be rendered in base-10 digits, x and X require an integer and will render it as hexadecimal digits, o requires an integer and will render it as octal digits, b requires an integer and will render it as binary digits, s requires a string (almost never used).

    Note

    When a numeric type can render alphabetic characters, such as hex strings or special values like infinity, the lowercase version of the type forces lowercase alphabetics and the uppercase version forces uppercase alphabetics.

    Note

    In most cases, it's best to leave the format type empty. Floats will be rendered by default as g, integers will be rendered by default as d, and s is almost always redundant. There are only three cases where specifying a type is recommended:

  • format strings are parsed at compile time, so specifying a type can help detect errors then

  • format strings default to using lowercase letters for hex digits and the e in exponents. Use a uppercase type to force the use of uppercase hex digits and an uppercase E in exponents.

  • format strings are the most convenient way to get hex, binary or octal strings from an integer.

See Format Placeholder Specification for more information.

Scientific float interpolation (e, E, g, or G) uses at least two exponent digits, without additional leading zeroes, including when a precision is specified.

x := 123.4567 println('[${x:.2}]') // round to two decimal places => [123.46] println('[${x:10}]') // right-align with spaces on the left => [ 123.457] println('[${int(x):-10}]') // left-align with spaces on the right => [123 ] println('[${int(x):010}]') // pad with zeros on the left => [0000000123] println('[${int(x):+05}]') // include the sign in the padded width => [+0123] println('[${x:+08.2f}]') // sign, zero padding, and precision => [+0123.46] println('[${x:-+010.2f}]') // sign and left alignment override zero padding => [+123.46 ] println('[${int(x):b}]') // output as binary => [1111011] println('[${int(x):o}]') // output as octal => [173] println('[${int(x):X}]') // output as uppercase hex => [7B] println('[${10.0000:.2}]') // remove insignificant 0s at the end => [10] println('[${10.0000:.2f}]') // do show the 0s at the end, even though they do not change the number => [10.00]

V also has r and R switches, which will repeat the string the specified amount of times.

println('[${'abc':3r}]') // [abcabcabc] println('[${'abc':3R}]') // [ABCABCABC]

String operators

name := 'Bob' bobby := name + 'by' // + is used to concatenate strings println(bobby) // "Bobby" mut s := 'hello ' s += 'world' // `+=` is used to append to a string println(s) // "hello world"

All operators in V must have values of the same type on both sides. You cannot concatenate an integer to a string:

age := 10 println('age = ' + age) // not allowed

error: infix expr: cannot use int (right expression) as string

We have to either convert age to a string:

age := 11 println('age = ' + age.str())

or use string interpolation (preferred):

age := 12 println('age = ${age}')

See all methods of string and related modules strings, strconv.

Runes

A rune represents a single UTF-32 encoded Unicode character and is an alias for u32. To denote them, use ` (backticks) :

rocket := `🚀`

A rune can be converted to a UTF-8 string by using the .str() method.

rocket := `🚀` assert rocket.str() == '🚀'

A rune can be converted to UTF-8 bytes by using the .bytes() method.

rocket := `🚀` assert rocket.bytes() == [u8(0xf0), 0x9f, 0x9a, 0x80]

Hex, Unicode, and Octal escape sequences also work in a rune literal:

assert `\x61` == `a` assert `\141` == `a` assert `\u0061` == `a` // multibyte literals work too assert `\u2605` == `★` assert `\u2605`.bytes() == [u8(0xe2), 0x98, 0x85] assert `\xe2\x98\x85`.bytes() == [u8(0xe2), 0x98, 0x85] assert `\342\230\205`.bytes() == [u8(0xe2), 0x98, 0x85]

Note that rune literals use the same escape syntax as strings, but they can only hold one unicode character. Therefore, if your code does not specify a single Unicode character, you will receive an error at compile time.

Also remember that strings are indexed as bytes, not runes, so beware:

rocket_string := '🚀' assert rocket_string[0] != `🚀` assert 'aloha!'[0] == `a`

A string can be converted to runes by the .runes() method.

hello := 'Hello World 👋' hello_runes := hello.runes() // [`H`, `e`, `l`, `l`, `o`, ` `, `W`, `o`, `r`, `l`, `d`, ` `, `👋`] assert hello_runes.string() == hello

Numbers

a := 123

This will assign the value of 123 to a. By default a will have the type int.

You can also use hexadecimal, binary or octal notation for integer literals:

a := 0x7B b := 0b01111011 c := 0o173

All of these will be assigned the same value, 123. They will all have type int, no matter what notation you used.

V also supports writing numbers with _ as separator:

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

If you want a different type of integer, you can use casting:

a := i64(123) b := u8(42) c := i16(12345)

Assigning floating point numbers works the same way:

f := 1.0 f1 := f64(3.14) f2 := f32(3.14)

If you do not specify the type explicitly, by default float literals will have the type of f64.

Integer literals can be assigned to f32 and f64 variables without a cast. Unary +, unary -, parentheses, and arithmetic on integer literals and on the constants declared with them preserve this behavior:

const tile_size = 32 mut a := f32(0) a = 1 a = -1 assert a == f32(-1) a = 6 * tile_size assert a == f32(192)

This does not make typed integer variables implicitly assignable to f32; use an explicit conversion such as a = f32(value) for those variables.

Float literals can also be declared as a power of ten:

f0 := 42e1 // 420 f1 := 123e-2 // 1.23 f2 := 456e+2 // 45600

Checked integer arithmetic

Integer arithmetic wraps on overflow, a shift by the bit width or more gives 0, and a cast to a smaller integer type keeps the low bits. Two opt-in flags turn these into runtime panics:

  • v -check-overflow checks +, -, *, ++, --, and min / -1 and min % -1 (with their compound forms like -=, /=). In code outside the standard library, it also checks the negation of the minimum value (-x for x == min_i64), and shifts whose count is negative or not less than the bit width of the left operand.
  • v -check-casts checks integer casts that lose information, like i8(i64(300)), u8(-1) or u64(i64(-5)). Casts from floats, or to char and enums, are not checked. Only code outside the standard library is checked, since vlib uses truncating casts on purpose (hashes, byte extraction).

A function tagged with @[ignore_overflow] is not checked by either flag:

@[ignore_overflow] fn hash_step(h u32, b u8) u32 { return (h ^ u32(b)) * 16777619 // wraps on purpose }

Arrays

Returning a new array through helper calls preserves each helper's parameter scope.

An array is a collection of data elements of the same type. An array literal is a list of expressions surrounded by square brackets. An individual element can be accessed using an index expression. Indexing starts from 0.

A string literal keeps its string type even when its text names a type alias. For example, ['Speed'] contains strings, while [Speed(7)] contains Speed values.

After an array literal, separate && from either adjacent token with whitespace or a comment to use logical AND, as in a == [] && flag. An attached []&&Type{} declares an array of references to references. Separate & on both sides to use the binary AND operator; []&Type{} and [] &Type{} remain array initializers with reference elements.

mut nums := [10, 20, 30] println(nums) // `[10, 20, 30]` println(nums[0]) // `10` println(nums[1]) // `20` nums[1] = 5 println(nums) // `[10, 5, 30]`

An element can be appended to the end of an array using the push operator <<. It can also append an entire array.

The C backend uses typed stores for scalar element assignments and single-element appends. Assignments retain bounds checking. Appends retain capacity checks and detach slice storage when needed. The right-hand side can grow the array before the final element address is resolved.

mut nums := [1, 2, 3] nums << 4 println(nums) // "[1, 2, 3, 4]" // append array nums << [5, 6, 7] println(nums) // "[1, 2, 3, 4, 5, 6, 7]"

Use << ...array to explicitly append the array's elements. When appending an array of concrete values to an empty interface array, << array appends the whole array as one interface value, while << ...array converts and appends each element separately. For example, with interface Value {}, appending ['IT'] to []Value{} produces [Value(['IT'])] with << and [Value('IT')] with << .... insert(index, ...array) and prepend(...array) also convert each source element to the destination element type before inserting it.

mut names := ['John'] names << 'Peter' names << 'Sam' // names << 10 <-- This will not compile. `names` is an array of strings.

val in array returns true if the array contains val. See in operator.

names := ['John', 'Peter', 'Sam'] println('Alex' in names) // "false"

Use << ...array to explicitly append the array's elements. For an interface array, << array can append the whole array as one interface value, while << ...array converts each element separately. array.insert(index, ...values) and array.prepend(...values) also convert each source element to the destination element type.

Array Fields

There are two fields that control the "size" of an array:

  • len: length - the number of pre-allocated and initialized elements in the array
  • cap: capacity - the amount of memory space which has been reserved for elements, but not initialized or counted as elements. The array can grow up to this size without being reallocated. Usually, V takes care of this field automatically but there are cases where the user may want to do manual optimizations (see below).
mut nums := [1, 2, 3] println(nums.len) // "3" println(nums.cap) // "3" or greater nums = [] // The array is now empty println(nums.len) // "0"

data is a field (of type voidptr) with the address of the first element. This is for low-level unsafe code.

[!NOTE] Fields are read-only and can't be modified by the user.

Array Initialization

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).

The user can explicitly specify the type for the first element: [u8(16), 32, 64, 128]. V arrays are homogeneous (all elements must have the same type). This means that code like [1, 'a'] will not compile.

Array elements must be written inside square brackets. Braces accept named initializer parameters only; []int{1, 2, 3} and [3]int{1, 2, 3} are syntax errors. Use [1, 2, 3] for a dynamic array or [1, 2, 3]! for a fixed array instead.

The above syntax is fine for a small number of known elements but for very large or empty arrays there is a second initialization syntax:

mut a := []int{len: 10000, cap: 30000, init: 3}

This creates an array of 10000 int elements that are all initialized with 3. Memory space is reserved for 30000 elements. The parameters len, cap and init are optional; len defaults to 0 and init to the default initialization of the element type (0 for numerical type, '' for string, etc). The run time system makes sure that the capacity is not smaller than len (even if a smaller value is specified explicitly):

arr := []int{len: 5, init: -1} // `arr == [-1, -1, -1, -1, -1]`, arr.cap == 5 // Declare an empty array: users := []int{}

Setting the capacity improves performance of pushing elements to the array as reallocations can be avoided:

mut numbers := []int{cap: 1000} println(numbers.len) // 0 // Now appending elements won't reallocate for i in 0 .. 1000 { numbers << i }

[!NOTE] The above code uses a range for statement.

You can initialize the array by accessing the index variable which gives the index as shown here:

count := []int{len: 4, init: index} assert count == [0, 1, 2, 3] mut square := []int{len: 6, init: index * index} // square == [0, 1, 4, 9, 16, 25]

Array update syntax

V lets you initialise an array by spreading an existing array, optionally followed by additional elements:

base := [1, 2] a := [...base, 3, 4] assert a == [1, 2, 3, 4] // Append to a copy of `base`, leaving `base` itself unchanged: mut b := [...base] b << 99 assert base == [1, 2] assert b == [1, 2, 99]

This is functionally equivalent to cloning the array and appending to it, except that you don't have to declare a mutable variable for the intermediate value, and the additional elements may be inlined at the call site.

Array Types

An array can be of these types:

Types Example Definition
Number []int,[]i64
String []string
Rune []rune
Boolean []bool
Array [][]int
Struct []MyStructName
Channel []chan f64
Function []MyFunctionType []fn (int) bool
Interface []MyInterfaceName
Sum Type []MySumTypeName
Generic Type []T
Map []map[string]f64
Enum []MyEnumType
Alias []MyAliasTypeName
Thread []thread int
Reference []&f64
Shared []shared MyStructType
Option []?f64

Example Code:

This example uses Structs and Sum Types to create an array which can handle different types (e.g. Points, Lines) of data elements.

struct Point { x int y int } struct Line { p1 Point p2 Point } type ObjectSumType = Line | Point mut object_list := []ObjectSumType{} object_list << Point{1, 1} object_list << Line{ p1: Point{3, 3} p2: Point{4, 4} } dump(object_list) /* object_list: [ObjectSumType(Point{ x: 1 y: 1 }), ObjectSumType(Line{ p1: Point{ x: 3 y: 3 } p2: Point{ x: 4 y: 4 } })] */

Multidimensional Arrays

Arrays can have more than one dimension.

2d array example:

mut a := [][]int{len: 2, init: []int{len: 3}} a[0][1] = 2 println(a) // [[0, 2, 0], [0, 0, 0]]

3d array example:

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]]]

Array methods

A function literal passed to map uses its return type for the output elements. Its parameters and nested array expressions have their own scope, including parameters named it.

All arrays can be easily printed with println(arr) and converted to a string with s := arr.str().

Copying the data from the array is done with .clone():

nums := [1, 2, 3] nums_copy := nums.clone()

Arrays can be efficiently filtered and mapped with the .filter() and .map() methods:

nums := [1, 2, 3, 4, 5, 6] even := nums.filter(it % 2 == 0) println(even) // [2, 4, 6] // filter can accept anonymous functions even_fn := nums.filter(fn (x int) bool { return x % 2 == 0 }) println(even_fn)
words := ['hello', 'world'] upper := words.map(it.to_upper()) println(upper) // ['HELLO', 'WORLD'] // map can also accept anonymous functions upper_fn := words.map(fn (w string) string { return w.to_upper() }) println(upper_fn) // ['HELLO', 'WORLD']

it is a builtin variable which refers to the element currently being processed in filter/map methods.

Additionally, .any() and .all() can be used to conveniently test for elements that satisfy a condition.

nums := [1, 2, 3] println(nums.any(it == 2)) // true println(nums.all(it >= 2)) // false

There are further built-in methods for arrays:

  • a.repeat(n) concatenates the array elements n times
  • a.insert(i, val) inserts a new element val at index i and shifts all following elements to the right
  • a.insert(i, [3, 4, 5]) inserts several elements
  • a.prepend(val) inserts a value at the beginning, equivalent to a.insert(0, val)
  • a.prepend(arr) inserts elements of array arr at the beginning
  • a.trim(new_len) truncates the length (if new_length < a.len, otherwise does nothing)
  • a.clear() empties the array without changing cap (equivalent to a.trim(0))
  • a.delete_many(start, size) removes size consecutive elements from index start, preserving order. On the C backend, it reuses the backing buffer and keeps capacity when no slices share it
  • a.delete(index) equivalent to a.delete_many(index, 1)
  • a.delete_last() removes the last element; on the C backend it does not change cap
  • a.first() equivalent to a[0]
  • a.last() equivalent to a[a.len - 1]
  • a.pop() removes the last element and returns it
  • a.reverse() makes a new array with the elements of a in reverse order
  • a.reverse_in_place() reverses the order of elements in a
  • a.join(joiner) concatenates an array of strings into one string using joiner string as a separator

See all methods of array

See also vlib/arrays.

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.

mut numbers := [1, 3, 2] numbers.sort() // 1, 2, 3 numbers.sort(a > b) // 3, 2, 1

sorted() returns a sorted copy. Alias element types keep their overloaded < operator, including when the receiver is an array literal or a parenthesized array literal.

struct User { age int name string } mut users := [User{21, 'Bob'}, User{20, 'Zarkon'}, User{25, 'Alice'}] 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

V also supports custom sorting, through the sort_with_compare array method. Which expects a comparing function which will define the sort order. Useful for sorting on multiple fields at the same time by custom sorting rules. The code below sorts the array ascending on name and descending age.

struct User { age int name string } mut users := [User{21, 'Bob'}, User{65, 'Bob'}, User{25, 'Alice'}] custom_sort_fn := fn (a &User, b &User) int { // return -1 when a comes before b // return 0, when both are in same order // return 1 when b comes before a if a.name == b.name { if a.age < b.age { return 1 } if a.age > b.age { return -1 } return 0 } if a.name < b.name { return -1 } else if a.name > b.name { return 1 } return 0 } users.sort_with_compare(custom_sort_fn)

Array Slices

Iteration over an array slice keeps the array's element type: iterating []string yields strings, including when the containing function is reached through generic calls.

A slice is a part of a parent array. Initially it refers to the elements between two indices separated by a .. operator. The right-side index must be greater than or equal to the left side index.

If a right-side index is absent, it is assumed to be the array length. If a left-side index is absent, it is assumed to be 0.

nums := [0, 10, 20, 30, 40] println(nums[1..4]) // [10, 20, 30] println(nums[..4]) // [0, 10, 20, 30] println(nums[1..]) // [10, 20, 30, 40]

In V slices are arrays themselves (they are not distinct types). As a result all array operations may be performed on them. E.g. they can be pushed onto an array of the same type:

array_1 := [3, 5, 4, 7, 6] mut array_2 := [0, 1] array_2 << array_1[..3] println(array_2) // `[0, 1, 3, 5, 4]`

A slice is always created with the smallest possible capacity cap == len (see cap above) no matter what the capacity or length of the parent array is. As a result it is immediately reallocated and copied to another memory location when the size increases thus becoming independent from the parent array (copy on grow). In particular pushing elements to a slice does not alter the parent:

When a slice expression like a[2..4] is assigned outside unsafe and either the parent array or the resulting slice is mutable, V inserts an implicit .clone() and shows a notice. This prevents changes through one array from affecting the other. If both arrays are immutable, the slice safely reuses the parent array's memory without cloning. The shared-memory examples below therefore use unsafe {} intentionally.

mut a := [0, 1, 2, 3, 4, 5] // Create a slice, that reuses the *same memory* as the parent array // initially, without doing a new allocation: mut b := unsafe { a[2..4] } // the contents of `b`, reuses the memory, used by the contents of `a`. b[0] = 7 // Note that `b[0]` and `a[2]` refer to *the same element* in memory. println(a) // `[0, 1, 7, 3, 4, 5]` - changing `b[0]` above, changed `a[2]` too. // the content of `b` will get reallocated, to have room for the `9` element: b << 9 // The content of `b`, is now reallocated, and fully independent from the content of `a`. println(a) // `[0, 1, 7, 3, 4, 5]` - no change, since the content of `b` was reallocated, // to a larger block, before the appending. println(b) // `[7, 3, 9]` - the contents of `b`, after the reallocation, and appending of the `9`.

Appending to the parent array, may or may not make it independent from its child slices. The behaviour depends on the parent's capacity and is predictable:

mut a := []int{len: 5, cap: 6, init: 2} mut b := unsafe { a[1..4] } // the contents of `b` uses part of the same memory, that is used by `a` too a << 3 // still no reallocation of `a`, since `a.len` still fits in `a.cap` b[2] = 13 // `a[3]` is modified, through the slice `b`. a << 4 // the content of `a` has been reallocated now, and is independent from `b` (`cap` was exceeded by `len`) b[1] = 3 // no change in `a` println(a) // `[2, 2, 2, 13, 2, 3, 4]` println(b) // `[2, 3, 13]`

You can call .clone() on the slice, if you do want to have an independent copy right away:

mut a := [0, 1, 2, 3, 4, 5] mut b := a[2..4].clone() b[0] = 7 // Note: `b[0]` is NOT referring to `a[2]`, as it would have been, without the `.clone()` println(a) // [0, 1, 2, 3, 4, 5] println(b) // [7, 3]

If either the parent array or the slice is mutable, V makes an implicit clone of the slice and displays a notice. Therefore, without the .clone() call, the result of the code above will be the same. When both arrays are immutable, the slice reuses the parent array's memory because neither array can be changed. Make the slice in an unsafe {} block if you want to share mutable memory; otherwise use explicit cloning.

Slices with negative indexes

V supports array and string slices with negative indexes. Negative indexing starts from the end of the array towards the start, for example -3 is equal to array.len - 3. Negative slices have a different syntax from normal slices, i.e. you need to add a gate between the array name and the square bracket: a#[..-3]. The gate specifies that this is a different type of slice and remember that the result is "locked" inside the array. The returned slice is always a valid array, though it may be empty:

a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] println(a#[-3..]) // [7, 8, 9] println(a#[-20..]) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] println(a#[-20..-8]) // [0, 1] println(a#[..-3]) // [0, 1, 2, 3, 4, 5, 6] // empty arrays println(a#[-20..-10]) // [] println(a#[20..10]) // [] println(a#[20..30]) // []

Array method chaining

You can chain the calls of array methods like .filter() and .map() and use the it built-in variable to achieve a classic map/filter functional paradigm:

// using filter, map and negatives array slices files := ['pippo.jpg', '01.bmp', '_v.txt', 'img_02.jpg', 'img_01.JPG'] filtered := files.filter(it#[-4..].to_lower() == '.jpg').map(it.to_upper()) // ['PIPPO.JPG', 'IMG_02.JPG', 'IMG_01.JPG']

Fixed size arrays

Mapping a fixed size array preserves its length and uses the mapping expression or function return type as its element type. Filtering still produces a dynamic array.

V also supports arrays with fixed size. Unlike ordinary arrays, their length is constant. You cannot append elements to them, nor shrink them. You can only modify their elements in place.

However, access to the elements of fixed size arrays is more efficient, they need less memory than ordinary arrays, and unlike ordinary arrays, their data is on the stack, so you may want to use them as buffers if you do not want additional heap allocations.

Most methods are defined to work on ordinary arrays, not on fixed size arrays. You can convert a fixed size array to an ordinary array with slicing:

mut fnums := [3]int{} // fnums is a fixed size array with 3 elements. fnums[0] = 1 fnums[1] = 10 fnums[2] = 100 println(fnums) // => [1, 10, 100] println(typeof(fnums).name) // => [3]int fnums2 := [1, 10, 100].to_fixed_size() // explicit conversion syntax fnums3 := [1, 10, 100]! // short init syntax, equivalent to `.to_fixed_size()` anums := fnums[..] // same as `anums := fnums[0..fnums.len]` println(anums) // => [1, 10, 100] println(typeof(anums).name) // => []int

Whole fixed size arrays and their ranges can be passed to mutable array parameters. These arguments borrow the original elements, so writes through either the array parameter or another alias are immediately visible through both. Returned or stored views keep sharing those elements. Local storage is moved to the heap before references to it are formed, so retained views remain valid after the local goes out of scope. A callee can also retain a reference to the separately allocated array header. Growing or reassigning that header follows the usual array slice rules and leaves the original fixed array's size unchanged. Immutable array-reference parameters, including each variadic argument, also borrow the original elements. These rules also apply to array-reference parameters declared through aliases. Fixed array values introduced by guards, multi-declarations, loop bindings, or select receives also receive durable storage when passed to a retaining array-reference parameter. Indexed fixed elements of dynamic arrays retain their original backing buffer, including through managed slice aliases, so retained headers preserve writes and remain valid after owner cleanup. The same rule applies to fixed elements obtained through first() or last(). Fixed values read from maps, including inline fields, are copied into independent durable storage. Mutable iteration over those fixed elements preserves the same backing lifetime. Pointer fields and indexed pointers retain the original fixed-array roots recorded by their owners. Borrowing does not clone elements or require a clone() method.

Passing a local struct's fixed-array storage by reference keeps the local on the stack when the called function only reads or writes scalar fields and array elements, or passes the reference, or the address of an element (&buf[i]), straight on to a function that does the same. Calls that may retain the storage still move it to the heap; -warn-about-allocs reports these moves. Calls through local function values remain conservative, including values that shadow function names. Explicitly destroying owned source elements invalidates views of those elements, as with other borrowed slices. With ownership checking enabled, returning or storing a view copies its buffer to independent storage. Owned elements are cloned so the retained value has independent owners. Retained array references, including those stored inside options, receive a separate header, so other aliases in the callee still share the original elements. An operation that detaches a borrowed buffer also clones its owned elements. Such elements need a compatible clone() method or IClone support. Retaining or detaching a nonempty uncloneable borrowed buffer panics; borrowing it or changing its elements in place is allowed. An empty view can grow without cloning any source elements.

Note that slicing will cause the data of the fixed size array to be copied to the newly created ordinary array. The exception is a slice that is written to: passing it as a mut argument, changing its elements, iterating over it with for mut, or calling sort(), sort_with_compare() or reverse_in_place() on it, updates the fixed size array itself:

fn fill(mut a []int) { for i in 0 .. a.len { a[i] = 9 } } mut fixed := [4, 3, 2, 1]! fill(mut fixed[2..]) println(fixed) // => [4, 3, 9, 9] fixed[..2].sort() println(fixed) // => [3, 4, 9, 9]

To copy elements into an existing array instead, use the builtin copy function. Like Go's copy, it copies as many elements as both arguments have, returns that number, and handles overlapping arguments. The destination can be an ordinary array, a fixed size array, or a slice of either, and is updated in place. The source can also be a string, when the destination holds bytes:

items := [1, 2, 3, 4, 5] mut fixed := [4]int{} println(copy(mut fixed, items)) // => 4 println(fixed) // => [1, 2, 3, 4] copy(mut fixed[2..], [9, 9, 9]) println(fixed) // => [1, 2, 9, 9] mut buf := []u8{len: 3} copy(mut buf, 'hello') println(buf.bytestr()) // => hel

Maps

Methods and references on map iteration values address the stored element, including nested maps. Postfix updates to a mutable map value field, such as m[key].level++, update the stored entry and insert a zero value first when the key is absent. The key is evaluated once.

mut m := map[string]int{} // a map with `string` keys and `int` values 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 println(m.keys()) // ['one', 'two'] m.delete('two')

Maps can have keys of type string, rune, integer, float, voidptr, enum, or fixed arrays of those supported key types. Struct keys are rejected, including when a generic key parameter is instantiated with a struct.

The whole map can be initialized using this short syntax:

numbers := { 'one': 1 'two': 2 } println(numbers)

If a key is not found, a zero value is returned by default:

sm := { 'abc': 'xyz' } val := sm['bad_key'] println(val) // ''
intm := { 1: 1234 2: 5678 } s := intm[3] println(s) // 0

It's also possible to use an or {} block to handle missing keys:

mm := map[string]int{} val := mm['bad_key'] or { panic('key not found') }

Modules can opt into stricter map indexing:

@[strict_map_index] module main fn main() { m := { 'abc': 'xyz' } value := m['abc'] or { panic('missing map key') } if other := m['abc'] { println(other) } // m['bad_key'] // compile error in `@[strict_map_index]` modules println(value) }

You can also check, if a key is present, and get its value, if it was present, in one go:

m := { 'abc': 'def' } if v := m['abc'] { println('the map value for that key is: ${v}') }

Note: map indexing returns a copy of the stored value, including with or {} and if v := m[key] {}. Mutating that local value does not update the value stored in the map.

To update a stored value, mutate m[key] directly or assign the modified value back to the map:

mut data := map[string][]int{} key := 'odd' value := 1 if _ := data[key] { data[key] << value } else { data[key] = [value] }

The same option check applies to arrays:

arr := [1, 2, 3] large_index := 999 val := arr[large_index] or { panic('out of bounds') } println(val) // you can also do this, if you want to *propagate* the access error: val2 := arr[333]! println(val2)

V also supports nested maps:

mut m := map[string]map[string]int{} m['greet'] = { 'Hello': 1 } m['place'] = { 'world': 2 } m['code']['orange'] = 123 print(m)

Maps are ordered by insertion, like dictionaries in Python. The order is a guaranteed language feature. This may change in the future.

See all methods of map and maps.

Map update syntax

As with structs, V lets you initialise a map with an update applied on top of another map:

const base_map = { 'a': 4 'b': 5 } foo := { ...base_map 'b': 88 'c': 99 } println(foo) // {'a': 4, 'b': 88, 'c': 99}

This is functionally equivalent to cloning the map and updating it, except that you don't have to declare a mutable variable:

// same as above (except mutable) mut foo := base_map.clone() foo['b'] = 88 foo['c'] = 99