Functions as values and types
The snippet can be accessed without any authentication.
Authored by
Kiryuu Sakuya
It's very useful when we use interfaces. As you can see testInt
is a variable that has a function as type and the returned values and arguments of filter
are the same as those of testInt
. Therefore, we can have complex logic in our programs, while maintaining flexibility in our code.
main.go 925 B
package main
import "fmt"
type testInt func(int) bool // define a function type of variable
/*
它的执行效果就是把 f 换成实际传入的函数,比如第 29 行展开大概是这样:
var result []int
for _, value := range slice {
if isOdd(value) {
result = append(result, value)
}
}
return result
*/
func isOdd(integer int) bool {
return integer%2 != 0
}
func isEven(integer int) bool {
return integer%2 == 0
}
// pass the function `f` as an argument to another function
func filter(slice []int, f testInt) []int {
var result []int
for _, value := range slice {
if f(value) {
result = append(result, value)
}
}
return result
}
var slice = []int{1, 2, 3, 4, 5, 7}
func main() {
odd := filter(slice, isOdd)
even := filter(slice, isEven)
fmt.Println("slice = ", slice)
fmt.Println("Odd elements of slice are: ", odd)
fmt.Println("Even elements of slice are: ", even)
}
Please register or sign in to comment