匿名函式

Golang 基礎: 匿名函式

函式指定給變數

package main

import "fmt"

func main() {
  // 函式指定給變數
	addFunction := func(a int, b int) int {
		return a + b
	}

  // 呼叫變數函式
	sum := addFunction(1, 2)

  // 3
	fmt.Println(sum)
}

Closure 閉包函式

package main

import "fmt"

func addFunction() func(a, b int) int {
	baseNumber := 10
	// baseNumber In addFunction()   0xc0000180c8 = 10
	fmt.Printf("baseNumber In addFunction()   %p = %d\n", &baseNumber, baseNumber)

	return func(a, b int) int {
		// baseNumber In addFunction() closure   0xc0000180c8 = 10
		fmt.Printf("baseNumber In addFunction() closure   %p = %d\n", &baseNumber, baseNumber)

		return func(a, b int) int {
			// baseNumber In addFunction() closure's closure   0xc0000180c8 = 10
			fmt.Printf("baseNumber In addFunction() closure's closure   %p = %d\n", &baseNumber, baseNumber)

			return baseNumber + a + b
		}(a, b)
	}
}

func main() {
	sum := addFunction()(1, 2)

	// 13
	fmt.Println(sum)
}

最後輸出的資料會長得像這樣

baseNumber In addFunction()   0xc0000180c8 = 10
baseNumber In addFunction() closure   0xc0000180c8 = 10
baseNumber In addFunction() closure's closure   0xc0000180c8 = 10
13

baseNumber 的變數在整個 Closure 裡面都可以取用,且都是指都一個變數