# 函式作為值

``````package main

import "fmt"

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
maximum := max
fmt.Println(max(10, 5))     // 10
fmt.Println(maximum(10, 5)) // 10
}
``````

``````package main

import "fmt"
import "reflect"

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
maximum := max
fmt.Println(reflect.TypeOf(max))     // func(int, int) int
fmt.Println(reflect.TypeOf(maximum)) // func(int, int) int
}
``````

# 宣告函式變數

``````package main

import "fmt"

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
var maximum func(int, int) int
fmt.Println(maximum) // nil

maximum = max
fmt.Println(maximum(10, 5)) // 10
}
``````

``````package main

import "fmt"

type BiFunc func(int, int) int // 定義了新型態

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
var maximum BiFunc
fmt.Println(maximum) // nil

maximum = max
fmt.Println(maximum(10, 5)) // 10
}
``````

``````package main

import "fmt"

type BiFunc = func(int, int) int // 型態別名宣告

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
var maximum BiFunc
fmt.Println(maximum) // nil

maximum = max
fmt.Println(maximum(10, 5)) // 10
}
``````

``````package main

import "fmt"

type BiFunc = func(int, int) int

func max(a, b int) int {
if a > b {
return a
}
return b
}

func main() {
var maximum BiFunc
fmt.Println(&maximum) // 0x1040a130
// fmt.Println(&max)
}
``````

# 回呼應用

``````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 greaterThan7(n int) bool {
return n > 7
}

func lessThan5(n int) bool {
return n < 5
}

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