Functions in Nim

Functions are central in Nim. We’ll learn about functions with a few different examples.

import std/strformat

# Here's a function that takes two ints and returns
# their sum as an int.
proc plus(a: int, b: int): int =
  # Nim has implicit returns, so we don't need to use
  # the return keyword if it's the last expression.
  a + b

# When you have multiple consecutive parameters of
# the same type, you can omit the type name for all
# but the last parameter.
proc plusPlus(a, b, c: int): int =
  a + b + c

# The main procedure is the entry point of the program
proc main() =
  # Call a function just as you'd expect, with
  # name(args).
  var res = plus(1, 2)
  echo fmt"1+2 = {res}"

  res = plusPlus(1, 2, 3)
  echo fmt"1+2+3 = {res}"

# Call the main procedure
main()

To run the program, save it as functions.nim and use the Nim compiler:

$ nim c -r functions.nim
1+2 = 3
1+2+3 = 6

There are several other features to Nim functions. One is multiple return values, which we’ll look at next.

Note: In Nim, functions are called procedures (proc). They can have implicit returns for the last expression, unlike Go which requires explicit returns. Nim also uses echo for printing to the console and string interpolation with fmt for formatting strings.