5. Functions

In this chapter, we discuss a core part of any language: functions. In Go, functions are first-class citizens that can be used in many ways. First, we show you how to create functions using the func keyword. Then we explain how to handle inbound arguments and return values. Finally, we cover advance function topics, such as variadic arguments, deferring functions, and the init function.

Function Definitions

Functions in Go resemble functions from most other programming languages. Listing 5.1 shows the definition of two functions: main and sayHello. It also shows two different function calls: sayHello() and fmt.Println("Hello").

Listing 5.1 A Program That Prints Hello

Get Go Fundamentals: Gopher Guides 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.