4. Functions — A Book of Go

Louis Petrik
2 min readMay 14, 2024
Source: the author

Functions are a way to write reusable code.

The absolute basics of functions in Go:

  • Can hold 0 or more arguments
  • Type is provided after the name of the parameter: func add(x int, y int)
  • A type for the return value must be provided
  • If a function is not returning anything (void), leave out the return type
func add(x int, y int) int {
return x + y
}

The returned type is written after the parentheses.

Parameters can be written in shortcut syntax:

func add(x, y int) int 

This is the same as func add(x int, y int) int.

Named return values

In Go, the returned values can be defined directly in the header of the function. To do so, we create parentheses instead of the return type, in which we define the named values which shall be returned. These named values exist as variables within the scope of this function.

Only in this case, xand y do not have to be declared right within the function:

func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}

--

--