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.