Skip to main content

Golang Functions

·241 words·2 mins·
Table of Contents
Lessons learned from `Learn Go with Tests` - This article is part of a series.
Part 4: This Article

Named return values
#

Golang supports named return values. In the following example golang automatically creates x & y as integers and returns them at the empty return statement. This is known as a naked return. Naked return statements should be used only in short functions. They can harm readability in longer functions.

package main

import "fmt"

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

func main() {
  x, y := split(6)
  fmt.Println(fmt.Sprintf("%v %v", x, y))
}
2 4

Variadic functions
#

Golang supports variadic functions. In short this is a function that can take an arbitrary amount of arguments.

package main

import "fmt"

func sum(nums ...int) {
  fmt.Print(nums, " ")
  total := 0

  for _, num := range nums {
    total += num
  }
  fmt.Println(total)
}

func main() {
  sum(1, 2)
  sum(1, 2, 3)

  nums := []int{1, 2, 3, 4}
  sum(nums...)
}
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

Defer
#

defer is a statement that tells goland to defer the execution of a function until the surrounding function returns, i.e. run it last. This is a great way to keep code readable, for example if you want the logic to close a server directly under the logic for starting it.

package main

import "fmt"

func main() {
	defer fmt.Println("Run this last")
	fmt.Println("Run this first")
}
Run this first
Run this last
Lessons learned from `Learn Go with Tests` - This article is part of a series.
Part 4: This Article