Chapter 4: Functions
This chapter covers everything you need to know about functions in Go: syntax, parameters, return values, scope, and best practices. Understanding functions is a key step toward writing modular and efficient Golang programs.
What You Will Learn in This Chapter
By the end of this chapter, you will understand:
- How to define and call functions
- Function parameters
- Multiple return values (a Go specialty)
- Named return values
- Variadic functions
- Anonymous functions
- Closures
- Higher-order functions
- Recursion
- Best practices for clean Go functions
This chapter is crucial — functions are the building blocks of all Go programs.
4.1 What Is a Function?
A function is a reusable block of code.
Think of it like a machine:
- You give it input
- It performs work
- It returns output
Example:
func greet() {
fmt.Println("Hello!")
}Calling it:
greet()4.2 Defining a Function
Basic structure:
func functionName() {
// body
}Example:
func sayHi() {
fmt.Println("Hi there")
}4.3 Functions With Parameters
Functions can receive inputs.
func greet(name string) {
fmt.Println("Hello", name)
}Call it:
greet("Alice")Multiple parameters:
func add(a int, b int) {
fmt.Println(a + b)
}Go lets you shorten type declarations:
func add(a, b int) {
fmt.Println(a + b)
}4.4 Functions With Return Values
Functions can return data.
func add(a int, b int) int {
return a + b
}Use it:
result := add(2, 3)
fmt.Println(result)4.5 Multiple Return Values (Go Superpower)
Go allows returning more than one value.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}Call it:
result, err := divide(10, 2)This is extremely common in Go.
4.6 Named Return Values
You can “name” your return variables inside the function definition:
func rectangleArea(width, height float64) (area float64) {
area = width * height
return
}Note:
The bare return returns the named values automatically.
Use named returns ONLY if they improve clarity.
4.7 Variadic Functions
Variadic = accepts any number of arguments.
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}Calling it:
sum(1, 2, 3)
sum(5, 7)
sum() // allowed! returns 0nums becomes a slice inside the function.
4.8 Anonymous Functions
Functions without names.
Get Aditya Rathore’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
func() {
fmt.Println("Hello from anonymous function")
}()Note the () at the end — they call the function immediately.
4.9 Closures (VERY IMPORTANT)
A closure is a function that remembers variables outside its scope.
Example:
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}Using it:
c := counter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
fmt.Println(c()) // 3Each call updates the same count variable — this is the power of closures.
Closures are heavily used in advanced Go (concurrency, APIs, data transforms).
4.10 Higher-Order Functions
These are functions that:
- Take functions as inputs
- Return functions
Example (passing a function):
func apply(f func(int) int, x int) int {
return f(x)
}Calling it:
square := func(n int) int { return n * n }
fmt.Println(apply(square, 5)) // 25🔁 4.11 Recursion
A function calling itself.
Example: factorial
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}Recursion is powerful but must be used carefully to avoid infinite loops.
🧹 4.12 Clean Code Principles for Functions
✔ Keep functions small: One function should do one thing.
✔ Use meaningful names — Bad: f(x, y) Good: calculatePrice(basePrice, discount)✔ Return errors, not panics: Go uses errors as values.
✔ Avoid too many parameters: If you have more than 4–5 parameters → use a struct.
✔ Avoid deep nesting
Use early returns:
if err != nil {
return err
}🌟 4.13 Summary of Chapter 4
You now understand:
- How to define functions
- Parameters & returns
- Multiple return values
- Named returns
- Variadic functions
- Anonymous functions
- Closures
- Higher-order functions
- Recursion
- Clean Go function practices
This is a major milestone — now you’re ready for Chapter 5: Data Structures (Arrays, Slices, Maps, Structs, Pointers).








