go,函數做爲參數類型

package main
import "fmt"

type testInt 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 testInt) []int {
	var result []int
	for _, value := range slice {
		if f(value) {//此處的參數 f 是函數類型,能夠直接當函數來用
			result = append(result, value)
		}
	}
	return result
}

func main(){
	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)
}
相關文章
相關標籤/搜索