Application 2018-10-04

About Golang Functions - Function Values / Callback Functions / Anonymous Functions

Understand Go functions: function values, callbacks, anonymous functions, and closures with practical implementation patterns.

Read in: ja
About Golang Functions - Function Values / Callback Functions / Anonymous Functions

Overview

In Golang functions, we will summarize the following three points.

Functions Treated as Function Values

package main

import (
  "fmt"
  "testing"
)

func sayHi() string {
  return "Hello"
}

func main() {
  greetA := sayHi()
  greetB := sayHi

  fmt.Println(greetA)
  fmt.Println(greetB())
}

Callback Functions

package main

import "fmt"

// Callback function
func add(n int) int {
    return n
}

func sum(v int, r func(int) int) int {
  return r(v)
}

func main() {
  fmt.Println(sum(1, add))
}

The function sum defines two arguments:

By the way, the add function being executed in the main function has its address stored.

fmt.Println("%v", add) // 0x10936d0

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

Definition of Anonymous Functions

Function Values

Example of treating an anonymous function as a function value

package main

import "fmt"

func main() {
  sum := func (n int) int {
    return n + 1
  }

  fmt.Println(sum(1))
}

Closures

Example of defining an anonymous function as a closure

package main

import "fmt"

func count() func() int {
  var count int
  return func() int {
    count++
    return count
  }
}

func main() {
  countUp := count()
  fmt.Println(countUp()) // 1
  fmt.Println(countUp()) // 2
  fmt.Println(countUp()) // 3
}

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

Thoughts

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

Tags: Golang Callback Function Anonymous Function
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles