V Types
Primitive types
[!NOTE] Unlike C and Go,
int
is always a 32 bit integer.
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:
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:
Strings
In V, a string is a read-only array of bytes. All Unicode characters are encoded using UTF-8:
String values are immutable. You cannot mutate elements:
error: cannot assign to
s[i]
since V strings are immutable
Note that indexing a string 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
:
If you want the code point from a specific string
index or other more advanced
utf8 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.
For raw strings, prepend r
. Escape handling is not done for raw strings:
Strings can be easily converted to integers:
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:
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 use0
as the padding character instead of the defaultspace
character.Note
V does not currently support the use of
'
or#
as format flags, and V supports but doesn't need+
to right-align since that's the default.width: may be an integer value describing the minimum width of total field to output.
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 af
specifier to the precision value (see examples below). Applies only to float variables and is ignored for integer variables.type:
f
andF
specify the input is a float and should be rendered as such,e
andE
specify the input is a float and should be rendered as an exponent (partially broken),g
andG
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
andX
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 asd
, ands
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 uppercaseE
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.
V also has r
and R
switches, which will repeat the string the specified amount of times.
String operators
All operators in V must have values of the same type on both sides. You cannot concatenate an integer to a string:
error: infix expr: cannot use
int
(right expression) asstring
We have to either convert age
to a string
:
or use string interpolation (preferred):
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) :
A rune
can be converted to a UTF-8 string by using the .str()
method.
A rune
can be converted to UTF-8 bytes by using the .bytes()
method.
Hex, Unicode, and Octal escape sequences also work in a rune
literal:
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:
A string can be converted to runes by the .runes()
method.
Numbers
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:
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:
If you want a different type of integer, you can use casting:
Assigning floating point numbers works the same way:
If you do not specify the type explicitly, by default float literals
will have the type of f64
.
Float literals can also be declared as a power of ten:
Arrays
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. Indexes start from 0
:
An element can be appended to the end of an array using the push operator <<
.
It can also append an entire array.
val in array
returns true if the array contains val
. See in
operator.
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 arraycap
: 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).
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.
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:
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):
Setting the capacity improves performance of pushing elements to the array as reallocations can be avoided:
[!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:
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 |
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.
Multidimensional Arrays
Arrays can have more than one dimension.
2d array example:
3d array example:
Array methods
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()
:
Arrays can be efficiently filtered and mapped with the .filter()
and
.map()
methods:
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.
There are further built-in methods for arrays:
a.repeat(n)
concatenates the array elementsn
timesa.insert(i, val)
inserts a new elementval
at indexi
and shifts all following elements to the righta.insert(i, [3, 4, 5])
inserts several elementsa.prepend(val)
inserts a value at the beginning, equivalent toa.insert(0, val)
a.prepend(arr)
inserts elements of arrayarr
at the beginninga.trim(new_len)
truncates the length (ifnew_length < a.len
, otherwise does nothing)a.clear()
empties the array without changingcap
(equivalent toa.trim(0)
)a.delete_many(start, size)
removessize
consecutive elements from indexstart
– triggers reallocationa.delete(index)
equivalent toa.delete_many(index, 1)
a.delete_last()
removes the last elementa.first()
equivalent toa[0]
a.last()
equivalent toa[a.len - 1]
a.pop()
removes the last element and returns ita.reverse()
makes a new array with the elements ofa
in reverse ordera.reverse_in_place()
reverses the order of elements ina
a.join(joiner)
concatenates an array of strings into one string usingjoiner
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.
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
.
Array Slices
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.
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:
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:
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:
You can call .clone() on the slice, if you do want to have an independent copy right away:
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:
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:
Fixed size arrays
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:
Note that slicing will cause the data of the fixed size array to be copied to the newly created ordinary array.
Maps
Maps can have keys of type string, rune, integer, float or voidptr.
The whole map can be initialized using this short syntax:
If a key is not found, a zero value is returned by default:
It's also possible to use an or {}
block to handle missing keys:
You can also check, if a key is present, and get its value, if it was present, in one go:
The same option check applies to arrays:
V also supports nested maps:
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:
This is functionally equivalent to cloning the map and updating it, except that you don't have to declare a mutable variable: