โš™๏ธFunctionsLESSON

Functions

Functions are the building blocks of Go programs. They encapsulate reusable logic and are declared with the func keyword.

Basic Function Syntax

A function declaration specifies the function name, parameters with their types, and the return type.

When consecutive parameters share the same type, you can group them: a, b int instead of a int, b int.

Multiple Return Values

One of Go's most distinctive features is the ability to return multiple values from a single function. This is especially powerful for error handling, eliminating the need for exceptions or out-parameters used in other languages.

The caller uses multiple assignment (:=) to capture both return values. By convention, the last return value is an error when the function can fail.

Named Return Values

Go allows you to name the return variables directly in the function signature. Named returns are initialized to their zero values and can be returned with a bare return statement.

Named return values serve as documentation โ€” the signature itself communicates what each value represents. However, avoid using bare returns in long functions, as they reduce readability by making it unclear what values are being returned.

Variadic Functions

A variadic function accepts any number of arguments of a given type using the ...T syntax. Inside the function, the variadic parameter behaves as a slice.

You can also expand an existing slice into variadic arguments using the ... spread syntax when calling the function.

Functions as First-Class Values

In Go, functions are first-class values โ€” they can be assigned to variables, passed as arguments to other functions, and returned from functions. This enables powerful patterns like callbacks, middleware, and higher-order functions, which you will explore in later modules.

Named Function Types

You can give a function signature a name with type. This is common for callbacks and middleware:

Named function types make signatures self-documenting and allow you to attach methods to function types โ€” a technique used by http.HandlerFunc in the standard library.

Method Values

When you access a method on a specific value, you get a method value โ€” a function bound to that receiver:

Method values are useful when you need to pass a method as a callback โ€” they capture the receiver automatically.

The init() Function

Go allows special init functions that run automatically before main:

Each package can have multiple init functions across multiple files; they run in the order they are imported. Keep init functions short and side-effect free โ€” avoid putting complex logic there.

Knowledge Check

How do you declare a function that returns two values in Go?

What operator makes a parameter variadic (accepts any number of arguments)?

What does a bare `return` statement do in a function with named return values?