Functions

  1. fn main() {
  2. println(add(77, 33))
  3. println(sub(100, 50))
  4. }
  5. fn add(x int, y int) int {
  6. return x + y
  7. }
  8. fn sub(x int, y int) int {
  9. return x - y
  10. }

Again, the type comes after the argument’s name.

Just like in Go and C, functions cannot be overloaded. This simplifies the code and improves maintainability and readability.

Functions can be used before their declaration: add and sub are declared after main, but can still be called from main. This is true for all declarations in V and eliminates the need for header files or thinking about the order of files and declarations.

Returning multiple values

  1. fn foo() (int, int) {
  2. return 2, 3
  3. }
  4. a, b := foo()
  5. println(a) // 2
  6. println(b) // 3
  7. c, _ := foo() // ignore values using `_`

Variable number of arguments

  1. fn sum(a ...int) int {
  2. mut total := 0
  3. for x in a {
  4. total += x
  5. }
  6. return total
  7. }
  8. println(sum()) // Output: 0
  9. println(sum(1)) // 1
  10. println(sum(2,3)) // 5