Functions in Go

By

Learn how to define and call functions in Go, set typed parameters, return one or multiple values, and write a variadic function that takes any number.

~~~

A function is a block of code that’s assigned a name, and contains some instructions. In Go you define one with the func keyword, and you call it by writing its name followed by parentheses.

In the “Hello, World!” example we created a main function, which is the entry point of the program:

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}

That’s a special function. Go runs it automatically when the program starts. You never call main yourself.

Usually we define functions with a custom name:

func doSomething() {

}

and then you can call them, like this:

doSomething()

Parameters

A function can accept parameters, and we have to set the type of each parameter:

func doSomething(a int, b int) {

}

doSomething(1, 2)

a and b are the names we associate to the parameters internally to the function.

When consecutive parameters share the same type, you can write the type once:

func doSomething(a, b int) {

}

Go is strict here. If you call the function with the wrong number of arguments, or the wrong types, the program does not compile.

Return values

A function can return a value, like this:

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

result := sumTwoNumbers(1, 2)

Note we specified the return value type

A function in Go can return more than one value:

func performOperations(a int, b int) (int, int) {
	return a + b, a - b
}

sum, diff := performOperations(1, 2)

It’s interesting because many languages only allow one return value.

This is used everywhere in Go. The standard library returns a result and an error together, and you check the error right after the call.

Here’s a pitfall: if you assign both values but only use one, the compiler stops with a declared and not used error. Go does not allow unused variables. When you don’t need one of the values, discard it with the blank identifier:

sum, _ := performOperations(1, 2)

Any variable defined inside the function is local to the function.

Variadic functions

A function can also accept an unlimited number of parameters, and in this case we call it a variadic function:

func sumNumbers(numbers ...int) int {
	sum := 0
	for _, number := range numbers {
		sum += number
	}
	return sum
}

total := sumNumbers(1, 2, 3, 4)

Inside the function, numbers is a slice of int values.

The variadic parameter must be the last one in the list. And if you already have a slice, you can pass it by adding ... after its name:

values := []int{1, 2, 3, 4}
total := sumNumbers(values...)
Tagged: Go · All topics
~~~

Related posts about go: