Chapter 5. Functions

So far, our programs have been limited to a few lines in the main function. It’s time to get bigger. In this chapter, we’re going to learn how to write functions in Go and see all of the interesting things we can do with them.

Declaring and Calling Functions

The basics of Go functions are familiar to anyone who has programmed in other languages with first-class functions, like C, Python, Ruby, or JavaScript. (Go also has methods, which we’ll cover in Chapter 7.) Just like control structures, Go adds its own twist on function features. Some are improvements and others are experiments that should be avoided. We’ll cover both in this chapter.

We’ve already seen functions being declared and used. Every program we’ve written has a main function that’s the starting point for every Go program, and we’ve been calling the fmt.Println function to display output to the screen. Since main functions don’t take in any parameters or return any values, let’s see what it looks like when we have a function that does:

func div(numerator int, denominator int) int {
    if denominator == 0 {
        return 0
    }
    return numerator / denominator
}

Let’s look at all the new things in this code sample. A function declaration has four parts: the keyword func, the name of the function, the input parameters, and the return type. The input parameters are listed in parentheses, separated by commas, with the parameter name first and the type second. Go is a typed language, ...

Get Learning Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.