Write reusable functions
Pass values to functions and return results.
- Define and call a function that returns a value.
A function packages a reusable operation. Parameters name the inputs and declare their types; the return type appears after the parameter list. Go functions can return multiple values, a common pattern for returning a result together with an error.
1package main
2
3import "fmt"
4
5func double(value int) int {
6 return value * 2
7}
8
9func main() {
10 fmt.Println(double(6))
11}12
The caller receives the value after return. A function can also return (value, error) so callers can handle failure explicitly instead of relying on exceptions.
Key takeaways
Define and call a function that returns a value.
Go catches many mistakes while compiling.
Use small experiments to understand each new language feature.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Go
Write Go in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Convert minutes to seconds
Write a function toSeconds that accepts minutes as an int and returns the number of seconds. Read a value and print the result.
- Two minutes
- Zero minutes
Go is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…