Go Tutorial: Functions
Stop repeating yourself. Write code once, name it, and call it anywhere.
Write it once, use it everywhere
Every program you have written so far is one big block of code inside `main`. That works for small programs. But as things grow, it becomes a mess.
Functions let you break your code into named, reusable pieces. Write the logic once, give it a name, call it whenever you need it.
Every serious program ever written is built from functions. This chapter is one of the most important ones.
Fourteen steps.
What you'll learn in this Go functions tutorial
This interactive Go tutorial has 11 hands-on exercises. Estimated time: 22 minutes.
- What is a function — Think about a library: you ask the librarian for a book and they bring it. You don't need to know how they find it.
- Parameters — make it flexible — A function with no parameters always does the same thing. A function with a parameter can adapt.
- Multiple parameters and return values 🤯 — Functions can take multiple parameters and return values.
- Named return values — Go lets you name the return values in the function signature. When you do, a bare `return` returns them automatically.
- Variadic functions (any number of args) — Sometimes you don't know how many arguments you'll get. `...int` means "zero or more ints."
- Pass a slice to a variadic function — What if you already have a slice of pages? Use `pages...` to expand the slice into individual arguments.
- Func as a value 🤯 — In Go, functions are values. You can store a function in a variable and call it later.
- Anonymous function (closure) — You can define and use a function inline without naming it. This is called an anonymous function.
- Pass a function as an argument — You can pass one function into another. `applyToBooks` takes a function that transforms a string.
- Recursion — a function that calls itself — Some problems are best solved by a function that calls itself. This is recursion.
- Build your own library function — Put it all together. Write a function `catalogBook(title string, pages int) string` that returns a formatted string: "Ti…
Go Functions concepts covered
- Write it once, use it everywhere