Functions

View saved

Define a function

Parameter types follow names. Name the return type after the parameter list.

func add(a int, b int) int {
	return a + b
}

fmt.Println(add(2, 3))

Return multiple values

Go commonly returns a result and an error together.

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, fmt.Errorf("divide by zero")
	}
	return a / b, nil
}

Named results and defer

Deferred calls run when the function returns—useful for cleanup.

func work() {
	defer fmt.Println("done")
	fmt.Println("working")
}

Function tips

  • Share consecutive parameter types: a, b int
  • Keep functions small and focused
  • Pass pointers when you need to modify a large struct
  • Variadic parameters use ...int

Comments

One comment per signed-in account. Comments are saved with this page’s URL.