Skip to main content

Functions

Functions

To write a function you would need to use the func keyword, provide the name of the funciton, provide in the argument of the function, and finally the return type of the function:

func plus(a int, b int) int {
  return a + b
}
Multiple return values

You can return multiple values in a function, however, you would need to explicit state what those return values are:

func vals() (int, int) [
  return 10, 20
}

In this case, the function vals will return two return values which are just simply two integers. Notice that the return types are surrounded by parenthesis, this is needed, if you only have one return value then you skip it.

Functions that takes in variable number of arguments

In Python, Java, JavaScript there is the concept of making function accept in a variable number of arguments, in Go there is that concept too.

And surprisingly it is also done with the same operator ... in most languages.

func sum(nums ...int) int {
  total := 0
  for _, num := range nums {
    total += num
  }
  return total
}

The type of nums will be []int.