# 匿名函式

``````package main

import "fmt"

type Predicate = func(int) bool

func filter(origin []int, predicate Predicate) []int {
filtered := []int{}
for _, elem := range origin {
if predicate(elem) {
filtered = append(filtered, elem)
}
}
return filtered
}

func main() {
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println(filter(data, func(elem int) bool {
return elem > 5
}))
fmt.Println(filter(data, func(elem int) bool {
return elem <= 6
}))
}
``````

``````func funcA() {
func funcB() {
...
}
...
}
``````

``````func funcA() {
funcB := func() {
...
}
...
}
``````

``````package main

import "fmt"

type Func1 = func(int) int

func funcA() Func1 {
x := 10
return func(n int) int {
return x + n
}
}

func main() {
fmt.Println(funcA()(2)) // 12
}
``````

# 閉包

``````package main

import "fmt"

type Consumer = func(int)

func forEach(elems []int, consumer Consumer) {
for _, elem := range elems {
consumer(elem)
}
}

func main() {
numbers := []int{1, 2, 3, 4, 5}
sum := 0
forEach(numbers, func(elem int) {
sum += elem
})
fmt.Println(sum) // 15
}
``````

``````package main

import "fmt"

type Consumer = func(int)

func forEach(elems []int, consumer Consumer) {
for _, elem := range elems {
consumer(elem)
}
}

func main() {
numbers := []int{1, 2, 3, 4, 5}
sum := 0
for _, elem := range numbers {
sum += elem
}
fmt.Println(sum) // 15
}
``````

``````package main

import "fmt"

type Getter = func() int
type Setter = func(int)

func x_getter_setter(x int) (Getter, Setter) {
getter := func() int {
return x
}
setter := func(n int) {
x = n
}
return getter, setter
}

func main() {
getX, setX := x_getter_setter(10)

fmt.Println(getX()) // 10
setX(20)
fmt.Println(getX()) // 20
}
``````

`x_getter_setter` 來說，`x` 參數也是變數，`x_getter_setter` 傳回了兩個匿名函式，這兩個匿名函式都形成了閉包，將 `x` 變數關閉在自己的範疇中，因此，你使用了 `setX(20)` 改變了 `x` 的值，使用 `getX()` 時取得的值，就會是修改後的值。

# 閉包與指標

``````package main

import "fmt"

type Getter = func() int
type Setter = func(int)

func x_getter_setter(x int) (Getter, Setter) {
fmt.Printf("the parameter :\tx (%p) = %d\n", &x, x)

getter := func() int {
fmt.Printf("getter invoked:\tx (%p) = %d\n", &x, x)
return x
}
setter := func(n int) {
x = n
fmt.Printf("setter invoked:\tx (%p) = %d\n", &x, x)
}
return getter, setter
}

func main() {
getX, setX := x_getter_setter(10)

fmt.Println(getX())
setX(20)
fmt.Println(getX())
}
``````

``````the parameter : x (0x104382e0) = 10
getter invoked: x (0x104382e0) = 10
10
setter invoked: x (0x104382e0) = 20
getter invoked: x (0x104382e0) = 20
20
``````