About Functions in Golang - Function Values, Callback Functions, and Anonymous Functions

Overview

This post summarizes the following aspects of functions in Golang:

  • Functions treated as function values
  • Functions that take other functions as arguments
  • Defining anonymous functions
    • Function values
    • Closures

Functions Treated as Function Values

Callback Functions

The sum function defines two arguments:

  • v, which is of type int
  • r, which is a function that takes an int as an argument and returns an int
    • When defining a callback function as an argument, you must specify the return type even if it is an argument.

Incidentally, the add function executed in the main function stores an address.

In PHP, callbacks were implemented using variable variables or call_user_func.

Defining Anonymous Functions

Function Values

An example of treating an anonymous function as a function value:

Closures

An example of defining an anonymous function as a closure:

Using closures allows the scope to remain open, so the value of count can be retained.

Thoughts

I realized I have been using callback functions without fully understanding them, so I want to delve deeper into how they work.