Go Functions Explained for Beginners

Updated 5 min read
Go Functions featured image: cards showing func, return and variadic inputs

Go functions let you wrap a piece of logic in a named block and reuse it anywhere in your program. In this post, you will learn how to write them, pass data in and get results back. Each idea comes with a short example that you can run yourself.

You have already used one function in every lesson: fmt.Println. Now you will build your own. Functions often hold loops and checks. So a quick look at loops in Go with range, break and continue and if, else and switch in Go will help.

What Are Go Functions?

A function is a named block of code that does one job. You write it once, and then you call it whenever you need that job done. To call a function means to run it by writing its name with brackets.

Think of a coffee machine. You put in water and beans, press a button, and get coffee back. Similarly, Go functions take inputs, do some work and hand back a result. As a bonus, they keep your code short and easy to test.

How to Write Go Functions

func greet(name string) {
	fmt.Println("Hello,", name)
}

func main() {
	greet("Smita") // Hello, Smita
}

First comes the keyword func, then the name, then the inputs in brackets. After that comes the body inside curly braces. Your program always starts from the special function main.

Parameters: Passing Data In

Parameters are the inputs a function expects. Each one has a name and a type, such as name string. When two parameters share a type, you can write the type once, as in width, height float64.

Return Values: Getting Data Out

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

func area(width, height float64) float64 {
	return width * height
}

fmt.Println(add(4, 6))    // 10
fmt.Println(area(2.5, 4)) // 10

The type after the brackets, like int, is the return type. The return keyword then sends the result back to the caller. So add(4, 6) becomes the value 10 wherever you use it.

Returning Many Values from Go Functions

Unlike many languages, Go lets one function return several values. Most often, the last one is an error, so the caller knows if something went wrong.

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return a / b, nil
}

result, err := divide(10, 0)
if err != nil {
	fmt.Println("Error:", err)
} else {
	fmt.Println(result)
}
// Error: cannot divide by zero

q, _ := divide(10, 2)
fmt.Println(q) // 5

Here nil means no error at all. Also notice the underscore in q, _, which throws away a value you do not need. The diagram below shows each part of this function.

Go Functions diagram showing the parts of the divide function and how a call returns two values

The caller sends 10 and 2 in, and the function sends back two values: 5 and nil.

Named Return Values

func minMax(nums []int) (min, max int) {
	min, max = nums[0], nums[0]
	for _, n := range nums {
		if n < min {
			min = n
		}
		if n > max {
			max = n
		}
	}
	return
}

lo, hi := minMax([]int{7, 2, 9, 4})
fmt.Println(lo, hi) // 2 9

You can give return values names, so they start as zero values inside the function. Then a bare return sends them back. This works well for short functions, but it can confuse readers in long ones.

Variadic Go Functions

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

fmt.Println(sum(1, 2, 3), sum(), sum(5, 5)) // 6 0 10

Variadic Go functions accept any number of inputs. The three dots in ...int turn all the inputs into a list. In fact, fmt.Println works this way, which is why it takes as many values as you like.

Functions as Values

square := func(x int) int {
	return x * x
}
fmt.Println(square(5)) // 25

In Go, you can store a function in a variable, just like a number. A function without a name is called an anonymous function. Later, you will pass these into other functions to sort lists or handle web requests.

Delaying Work with defer

func main() {
	defer fmt.Println("Goodbye")
	fmt.Println("Working...")
}
// Working...
// Goodbye

The defer keyword runs a call just before the function ends. For example, you can use it to close a file, so you never forget that step.

Common Mistakes with Go Functions

Error you seeWhy it happensHow to fix it
missing returnOne path ends without a return.Add a return at the end.
not enough arguments in call to addThe call passed fewer inputs.Pass every parameter.
assignment mismatch: 1 variable but divide returns 2 valuesOnly one variable catches two results.Write result, err := divide(…)

The last mistake is common for beginners. Go wants you to handle every returned value, even if you only throw it away with _. Function questions also appear in my Go interview questions and answers, so try them next.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go functions start with func, then a name, parameters, return types and a body.
  • A function can return several values, and the last one is usually an error.
  • Use _ to ignore a value you do not need.
  • Three dots like …int let a function take any number of inputs.
  • The defer keyword runs a call just before the function ends.

What’s Next?

Now you can write reusable code. Next, we will store many values together using arrays and slices, which you already met in this post.

Coming soon: Go Slices and Arrays Explained Simply