Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Return a function from a function in Go (Golang)

Posted on March 6, 2020March 6, 2020 by admin

In Golang function are first-order variables meaning that

  • They can be assigned to a variable
  • Passed around as function argument
  • Returned from a function

While returning a function from another function, the exact signature of the function has to be specified return list. As in below example

  • The return type of getAreaFunc function is func(int, int) int
func getAreaFunc() func(int, int)
  • getAreaFunc function hence it can return a function of type func(int, int) int

Code:

package main

import "fmt"

func main() {
    areaF := getAreaFunc()
    res := areaF(2, 4)
    fmt.Println(res)
}

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

Output:

8
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme