Golang 函式變數
在go中函式也是一種變數,可以通過type定義這種變數的型別。擁有相同引數和相同返回值的函式屬於同一種類型。
其優點是,既然是一種變數,我們就可以將函式作為值進行傳遞。
下面的例子中可以看到,函式isOdd和isEven作為引數傳遞給函式filter,使得filter函式更靈活。
type functionType func(int) bool // 聲明瞭一個函式型別 func isOdd(integer int) bool { if integer % 2 == 0 { return false } return true } func isEven(integer int) bool { if integer % 2 == 0 { return true } return false } // 宣告的函式型別在這個地方當做了一個引數 func filter(slice []int, f functionType) []int { var result []int for _, value := range slice { if f(value) { result = append(result, value) } } return result } func test(){ slice := []int {1, 2, 3, 4, 5, 7} fmt.Println("slice = ", slice) odd := filter(slice, isOdd)// 函式當做值來傳遞了 fmt.Println("Odd elements of slice are: ", odd) even := filter(slice, isEven)// 函式當做值來傳遞了 fmt.Println("Even elements of slice are: ", even) }