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 14 hands-on exercises. Estimated time: 22 minutes.
- What is a function — Think about a TV remote. You press the volume-up button and the volume goes up. You do not think about what happens insi…
- Define and call your own function — Now write one yourself.
- Parameters — give the function inputs — A function with no parameters always does exactly the same thing. More useful is a function that accepts inputs and does…
- Multiple parameters — Functions can take more than one parameter. Separate them with commas.
- Return a value — Functions can give something back using `return`.
- Multiple return values — Go can return more than one value from a function. This is one of Go's most useful features.
- Named return values — You can give return values names. This makes it clear what each one represents.
- Variadic functions — A variadic function accepts any number of arguments.
- Functions as values — In Go, functions are values. You can assign them to variables, store them in maps, pass them to other functions.
- Anonymous functions — An anonymous function has no name. It is defined and used inline.
- Closures — A closure is a function that remembers variables from the scope where it was created — even after that scope is gone.
- Recursion — A recursive function calls itself.
- defer — `defer` schedules a function call to run at the very end of the surrounding function — no matter what happens in between…
- Build a calculator — No starter code.
Go Functions concepts covered
- Write it once, use it everywhere