Functions as Parameters in Golang (AKA: When Functions Befriend Functions!)

Ever heard of functions passing around other functions like secret messages? Well, in Golang, functions can be treated like first-class citizens, meaning they can be assigned to variables, returned from other functions, and yes—passed as parameters!

In this guide, we’ll explore how to use functions as parameters, why they’re useful, and how to make your Go code more dynamic and reusable.

What are Functions as Parameters?

Functions can be passed as arguments to other functions, just like any other variable. This allows for:

  • Higher-order functions (functions that operate on other functions)
  • Customizable behavior without modifying function internals
  • Cleaner and more modular code

Think of it like hiring a personal chef:

  • You (the function caller) pass a recipe (function) to the chef (another function).
  • The chef follows the recipe (function) to cook something delicious.
  • You get to enjoy a meal without cooking yourself!

Defining a Function that Takes Another Function

Here’s the basic syntax:

func functionName(paramName func(paramType) returnType) {
    // Function body
}

This means paramName is expected to be a function with a specific signature.

Example: Passing a Function as a Parameter

Let’s create a function that takes another function as an argument:

package main
import "fmt"

func applyFunction(f func(int, int) int, a int, b int) int {
    return f(a, b)
}

func add(x, y int) int {
    return x + y
}

func multiply(x, y int) int {
    return x * y
}

func main() {
    fmt.Println(applyFunction(add, 3, 5))      // 8
    fmt.Println(applyFunction(multiply, 3, 5)) // 15
}

Output:

8
15

Here, applyFunction takes a function (f) and applies it to a and b. We can pass either add or multiply, making the function more flexible!

Anonymous Functions as Parameters

Instead of defining named functions, we can pass anonymous functions (functions without a name) directly as arguments.

func main() {
    result := applyFunction(func(x, y int) int {
        return x - y
    }, 10, 4)
    fmt.Println(result) // 6
}

This lets us define custom behavior on the spot, without needing extra function declarations!

Practical Use Case: Filtering a Slice

A common real-world use case is passing a function to filter elements in a slice.

func filter(nums []int, test func(int) bool) []int {
    var result []int
    for _, num := range nums {
        if test(num) {
            result = append(result, num)
        }
    }
    return result
}

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6}
    evens := filter(numbers, func(n int) bool { return n%2 == 0 })
    fmt.Println(evens) // [2 4 6]
}

Here, we pass a function that checks for even numbers, making filter super reusable!

Passing functions as parameters is a game-changer in Go. It allows for cleaner, modular, and more reusable code. Now go ahead and pass functions around like pro chefs sharing recipes! Happy coding! 

Post a Comment

0 Comments