Functions 2
Immutable function args by default
In V function arguments are immutable by default, and mutable args have to be marked on call.
Since there are also no globals, that means that the return values of the functions, are a function of their arguments only, and their evaluation has no side effects (unless the function uses I/O).
Function arguments are immutable by default, even when references are passed.
[!NOTE] However, V is not a purely functional language.
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
It is possible to modify function arguments by declaring them with the keyword mut
:
In this example, the receiver (which is just the first argument) is explicitly marked as mutable,
so register()
can change the user object. The same works with non-receiver arguments:
Note that you have to add mut
before nums
when calling this function. This makes
it clear that the function being called will modify the value.
It is preferable to return values instead of modifying arguments,
e.g. user = register(user)
(or user.register()
) instead of register(mut user)
.
Modifying arguments should only be done in performance-critical parts of your application
to reduce allocations and copying.
For this reason V doesn't allow the modification of arguments with primitive types (e.g. integers). Only more complex types such as arrays and maps may be modified.
Variable number of arguments
V supports functions that receive an arbitrary, variable amounts of arguments, denoted with the
...
prefix.
Below, a ...int
refers to an arbitrary amount of parameters that will be collected
into an array named a
.
Anonymous & higher order functions
Closures
V supports closures too. This means that anonymous functions can inherit variables from the scope they were created in. They must do so explicitly by listing all variables that are inherited.
Inherited variables are copied when the anonymous function is created. This means that if the original variable is modified after the creation of the function, the modification won't be reflected in the function.
However, the variable can be modified inside the anonymous function. The change won't be reflected outside, but will be in the later function calls.
If you need the value to be modified outside the function, use a reference.
Parameter evaluation order
The evaluation order of the parameters of function calls is NOT guaranteed. Take for example the following program:
V currently does not guarantee that it will print 100, 200, 300 in that order.
The only guarantee is that 600 (from the body of f
) will be printed after all of them.
This may change in V 1.0 .