Sling Academy
Home/Golang/Passing Functions as Arguments in Go

Passing Functions as Arguments in Go

Last updated: November 26, 2024

In Go, functions are first-class citizens, meaning you can assign them to variables, pass them as arguments to other functions, or return them from functions. This makes Go a powerful language for functional programming techniques. In this article, we'll delve into how you can pass functions as arguments in Go, starting from basic to more advanced examples.

Basic Example

Before passing a function as an argument, let’s see how you can define and call a simple function in Go.

package main

import "fmt"

func sayHello() {
    fmt.Println("Hello, World!")
}

func main() {
    sayHello()
}

This program defines a function sayHello that prints a simple message and calls it in main.

Passing Functions as Arguments

Next, let’s extend it by passing functions as arguments. This is useful when you want to make your functions more general and reusable.

package main

import "fmt"

func sayHello(name string) {
    fmt.Printf("Hello, %s!\n", name)
}

func greet(callback func(string), name string) {
    callback(name)
}

func main() {
    greet(sayHello, "Alice")
    greet(sayHello, "Bob")
}

In this example, greet is a higher-order function that takes another function callback and a string name as arguments. It calls the callback function with name. You can see how sayHello is used as an argument function and invoked with different names.

Intermediate Example: Using Anonymous Functions

Go also supports anonymous functions, which you can pass directly as arguments without defining them separately.

package main

import "fmt"

func greet(callback func(string), name string) {
    callback(name)
}

func main() {
    greet(func(name string) {
        fmt.Printf("Hi, %s!\n", name)
    }, "Charlie")
    
    greet(func(name string) {
        fmt.Printf("Welcome, %s!\n", name)
    }, "Dana")
}

Here, we call greet with inline anonymous functions rather than predefined functions. This flexibility allows creating custom behaviors on-the-fly.

Advanced Example: Returning Functions

You can even return functions from other functions, thus enhancing the functional nature of your code.

package main

import "fmt"

func createGreeter(salutation string) func(string) {
    return func(name string) {
        fmt.Printf("%s, %s!\n", salutation, name)
    }
}

func main() {
    sayHi := createGreeter("Hi")
    sayWelcome := createGreeter("Welcome")
    
    sayHi("Eve")
    sayWelcome("Frank")
}

In this advanced example, createGreeter returns a function which uses the captured salutation value. The returned function is called with a name, resulting in customized greeting messages.

Conclusion

Passing functions as arguments offers flexibility and modularity to Go programs. By mastering this technique, you can write cleaner and more reusable code.

Next Article: Returning Functions as Values in Go

Previous Article: Exploring Variadic Functions: Accepting Variable Arguments in Go

Series: Functions in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant