×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Functions as Values

Last Updated : July 19, 2025

In Go, functions are first-class citizens. This means you can assign functions to variables, pass them as arguments to other functions, and return them from functions - just like any other data type.

Assigning a Function to a Variable

You can store a function in a variable and call it using that variable.

Example

The following example shows how to assign a function to a variable in Go and call it using that variable:

package main
import "fmt"

func greet(name string) {
    fmt.Println("Hello", name)
}

func main() {
    var sayHello func(string)
    sayHello = greet
    sayHello("Amit")
}

When you run the above code, the output will be:

Hello Amit

Passing Functions as Arguments

Go allows you to pass functions as parameters to other functions. This is useful for callbacks or dynamic behavior.

Example

The following example demonstrates how to pass a function as an argument to another function in Go for performing custom operations:

package main
import "fmt"

func calculate(x int, y int, operation func(int, int) int) int {
    return operation(x, y)
}

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

func main() {
    result := calculate(10, 5, add)
    fmt.Println("Result =", result)
}

When you run the above code, the output will be:

Result = 15

Returning Functions from Functions

You can also return a function from another function in Go.

Example

The following example shows how to return a function from another function in Go, creating customized multiplier functions using closures:

package main
import "fmt"

func getMultiplier(factor int) func(int) int {
    return func(n int) int {
        return n * factor
    }
}

func main() {
    double := getMultiplier(2)
    triple := getMultiplier(3)

    fmt.Println("Double of 4:", double(4))
    fmt.Println("Triple of 4:", triple(4))
}

When you run the above code, the output will be:

Double of 4: 8
Triple of 4: 12

Exercise

Test your understanding of functions as values in Go:

  1. Can you store a function in a variable in Go?
  2. What keyword is used to declare an anonymous function?
  3. What does the getMultiplier function return in the above example?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.