Functions as Values
Start with Functions as Values
Functions have types in Go and can be assigned to variables, passed as arguments and returned as results. This helps separate an operation from the logic that chooses when to run it.
What you’ll learn
- Explain the main purpose of functions as values.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A function type records parameter and result types, such as func(int) int. Any function with the matching signature can be passed where that type is expected. A higher-order function accepts another function or returns one.
In the example, apply does not care how square computes its result; it simply calls the received operation. This is useful for transformations, validation rules and callbacks.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func square(n int) int { return n * n }
func triple(n int) int { return n * 3 }
func apply(value int, operation func(int) int) int {
return operation(value)
}
func main() {
fmt.Println("Square:", apply(5, square))
fmt.Println("Triple:", apply(5, triple))
}
Output
Square: 25
Triple: 15Trace what the program does
The first apply call receives the function value square and evaluates square(5) to 25. The next receives triple and returns 15. Passing square without parentheses passes the function, rather than calling it first.
Avoid common mistakes
squareis a function value, whilesquare(5)is a call producing an integer.- Parameter and result signatures must be compatible when assigning or passing function values.
Try it yourself
Add a decrement function and pass it into apply. Predict the output for input 5.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Functions as Values in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.