Functions and Multiple Returns
Name a job once, use it everywhere
You have been using functions since your first lesson: main is one, and fmt.Println is another. Now you get to write your own. A function wraps a set of steps behind a name, so you can run that job anywhere with one line.
A function that takes input and returns output
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(3, 4)
fmt.Println(sum)
}Reading the first line: a function named add takes two ints called a and b, and gives back one int. The return keyword sends the answer back to whoever called. In main, add(3, 4) runs the function with those values, and its answer lands in sum.
Small shortcut: when several parameters share a type, you can write it once at the end: func add(a, b int) int means the same thing.
Why functions matter
- No repetition: write the logic once, call it a hundred times.
- Readable names:
add(3, 4)says what it does at a glance. - Easy fixes: improve the function once, and every caller benefits.
Go's signature move: returning two things
Most languages let a function return only one value. Go functions can return several, and this is one of Go's most loved features:
func divmod(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q, r := divmod(17, 5)
fmt.Println("17 divided by 5 is", q, "remainder", r)
}The return type (int, int) promises two ints, and the caller catches both at once with q, r := .... That prints: 17 divided by 5 is 3 remainder 2.
Ignoring a value you do not need
If you only care about one of the returns, catch the other in an underscore, which is Go's official ignore-this sign:
q, _ := divmod(17, 5)Multiple returns are why Go error handling reads so cleanly. Real functions often return a result and an error together, like value, err := doSomething(), and then an if err != nil check decides what to do. You will meet that pattern the moment you read real Go code.
Quick check
Q1 What does the final int mean in func double(n int) int?
Q2 How do you catch both values from a function that returns two things?
Want to save your progress? It's free.
Create a free account