Functions 2

Pure functions by default

V functions are pure by default, meaning that their return values are a function of their arguments only, and their evaluation has no side effects (besides I/O).

This is achieved by a lack of global variables and all function arguments being immutable by default, even when references are passed.

V is not a purely functional language however.

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 using the keyword mut:

  1. struct User {
  2. name string
  3. mut:
  4. is_registered bool
  5. }
  6. fn (mut u User) register() {
  7. u.is_registered = true
  8. }
  9. mut user := User{}
  10. println(user.is_registered) // "false"
  11. user.register()
  12. println(user.is_registered) // "true"

In this example, the receiver (which is simply the first argument) is marked as mutable, so register() can change the user object. The same works with non-receiver arguments:

  1. fn multiply_by_2(mut arr []int) {
  2. for i in 0 .. arr.len {
  3. arr[i] *= 2
  4. }
  5. }
  6. mut nums := [1, 2, 3]
  7. multiply_by_2(mut nums)
  8. println(nums)
  9. // "[2, 4, 6]"

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

Use user.register() or user = register(user) instead of register(mut user).

V makes it easy to return a modified version of an object:

  1. struct User {
  2. name string
  3. age int
  4. is_registered bool
  5. }
  6. fn register(u User) User {
  7. return {
  8. u |
  9. is_registered: true
  10. }
  11. }
  12. mut user := User{
  13. name: 'abc'
  14. age: 23
  15. }
  16. user = register(user)
  17. println(user)

Anonymous & high order functions

  1. fn sqr(n int) int {
  2. return n * n
  3. }
  4. fn run(value int, op fn (int) int) int {
  5. return op(value)
  6. }
  7. fn main() {
  8. println(run(5, sqr)) // "25"
  9. // Anonymous functions can be declared inside other functions:
  10. double_fn := fn (n int) int {
  11. return n + n
  12. }
  13. println(run(5, double_fn)) // "10"
  14. // Functions can be passed around without assigning them to variables:
  15. res := run(5, fn (n int) int {
  16. return n + n
  17. })
  18. }