Functions
Learn how to define and use functions, including Go's powerful multiple return values
Learning Objectives
- Define and call basic functions
- Work with parameters and return types
- Return multiple values from a single function
- Use named return values
- Understand variadic functions
The Building Blocks of Go
Functions are central to Go. They allow you to group code into reusable units, making your programs more modular and easier to maintain.
Basic Function Syntax
Here’s how you define a function in Go:
|
|
Parameters and Return Values
If a function returns a value, you must specify the type after the parameters:
|
|
Shorthand for Parameters
When consecutive parameters have the same type, you can omit the type for all but the last one:
|
|
Multiple Return Values
One of Go’s most distinctive and powerful features is the ability for a function to return multiple values. This is frequently used for returning both a result and an error.
|
|
Named Return Values
Go’s return values can be named. If they are named, they are treated as variables defined at the top of the function. A return statement without arguments (called a “naked” return) will return the current values of the named return variables.
|
|
Variadic Functions
A variadic function can be called with any number of trailing arguments. fmt.Println is a common example. To define one, use ... before the type of the last parameter.
|
|
Function Scope and Pass by Value
In Go, everything is passed by value. This means that when you pass a variable to a function, Go creates a copy of that variable. Changes made inside the function do not affect the original variable (unless you use pointers, which we’ll cover later).
|
|
Summary
Today you learned:
- Basic function definition and calling
- Parameter shorthand syntax
- How to return multiple values from a function
- Using named return values for clarity
- Writing variadic functions with
... - Understanding that Go passes everything by value
Practice Exercise
- Write a function
calculatethat takes two integers and returns their sum, difference, and product. - Create a variadic function that finds the maximum value among the provided arguments.
- Write a function that takes a string and returns the string itself along with its length.
- Implement a function that calculates the area of a circle (given the radius) and returns both the area and an error if the radius is negative.
Next Steps
Tomorrow, we’ll wrap up our first week with a Review and Practice session to solidify everything you’ve learned!
Complete the quiz to wrap up Day 6!
Quiz
Complete this quiz with a minimum score of 80% to mark Day 6 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!