1.如下代码中的函数传参
package main
import "fmt"
func add1(a *int)int{
*a = *a + 1
return *a
}
type testInt func(int) bool // define a func type
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) {
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)
}
filter函数的第二个参数是函数,可以看到直接将isOdd, isEven传入了。
网友评论