References
References in V are similar to those in C++ and Go. You can read more about references in wiki article. Here we will describe some features of working with references in V.
References in V are specified by using the &
symbol in front of the type:
Take address
To create a reference, you need to take the address, e.g. of a variable or a field.
In V, this is done with the &
operator:
Now foo_ptr
is a reference to foo
.
Due to strict mutability rules, you cannot change the fields of the structure through such a reference, since the reference is immutable and is made for an immutable variable.
You can take a mutable reference from a mutable variable with which you can change fields:
Taking the address from an immutable variable and assigning it to a mutable reference is prohibited:
Dereferencing a reference
To get a value by reference, you can dereference the reference.
This is done with the *
operator:
Dereferencing a null reference will result in a fatal runtime error!
Print reference
In the output, the reference will have a &
at the beginning:
Unlike other languages, a value is displayed that is stored by reference.
To display the address of the reference, you should use
string interpolation
with p
format specifier:
Or use ptr_str()
function:
Null reference
Null references are references that do not point to any object. Dereferencing such references will result in a fatal runtime error.
Due to easy integration with C code, null references can be implicitly created in C code and then passed to V code. In such a case, the V code must be prepared for the fact that the reference may be null.
V has a nil
keyword that represents a null reference, but it can only be used in
unsafe
code:
To check for a null reference, you can use either the isnil
function or compare against nil
:
If you need to return a value or nil
from a function, or you want to represent a field that may
not be initialized, it is better to use
Option type,
which is much safer: