0
0
GoHow-ToBeginner · 3 min read

How to Pass Function as Argument in Go: Simple Guide

In Go, you can pass a function as an argument by specifying the function type in the parameter list using func keyword with its signature. This allows you to call the passed function inside another function just like any other variable.
📐

Syntax

To pass a function as an argument in Go, declare the parameter with the func keyword followed by the function's parameter and return types. Inside the function, you can call this parameter as a normal function.

  • func parameterName(func(paramTypes) returnType): Declares a function parameter.
  • funcVar(args): Calls the passed function.
go
func applyOperation(x int, y int, op func(int, int) int) int {
    return op(x, y)
}
💻

Example

This example shows how to pass a function that adds two numbers as an argument to another function that applies the operation.

go
package main

import "fmt"

func applyOperation(x int, y int, op func(int, int) int) int {
    return op(x, y)
}

func add(a int, b int) int {
    return a + b
}

func main() {
    result := applyOperation(5, 3, add)
    fmt.Println("Result:", result)
}
Output
Result: 8
⚠️

Common Pitfalls

Common mistakes include:

  • Not matching the function signature exactly in the parameter type.
  • Trying to pass a function with different parameters or return types.
  • Forgetting to call the function parameter with parentheses ().

Always ensure the function type matches exactly what the parameter expects.

go
package main

import "fmt"

// Wrong: function signature does not match
func applyOperation(x int, y int, op func(int) int) int {
    return op(x) // Missing second argument
}

func add(a int, b int) int {
    return a + b
}

func main() {
    // This will cause a compile-time error
    // result := applyOperation(5, 3, add)
    // fmt.Println("Result:", result)
}
📊

Quick Reference

Tips for passing functions as arguments in Go:

  • Use func keyword with exact parameter and return types.
  • Call the function parameter with parentheses and required arguments.
  • Functions are first-class citizens and can be assigned to variables or passed around.

Key Takeaways

Use the func keyword with matching signature to declare function parameters.
Call the passed function inside your function using parentheses and arguments.
Function signatures must match exactly to avoid compile errors.
Functions can be passed just like any other variable in Go.
Passing functions enables flexible and reusable code patterns.