个人github(golang学习笔记):https://github.com/fangguizhen/Notes/blob/master/Golang%E7%9F%A5%E8%AF%86%E7%82%B9.md
package main
//头等函数
//支持头等函数的编程语言,可以把函数赋值给变量,也可以把函数作为其他函数的参数或者返回值。Go语言支持头等函数的机制
//下面是头等函数的语法和用例
//一、匿名函数
/*func main() {
func(str string) {
fmt.Println("hello,golang", str)
}("hello,world")
}
//输出:hello,golang hello,world
*/
//二、用户自定义的函数类型
/*type add func(a int, b int) int
func main() {
//定义一个add类型的变量a
var a add
a = func(a int, b int) int {
return a + b
}
s := a(1, 2)
fmt.Println("sum=", s)
}
//输出:sum= 3
*/
//三、高阶函数
//高阶函数是满足下列条件之一的函数:
// 1、接收一个或多个函数作为参数
// 2、返回值是一个函数
//实例1、把函数作为参数,传递给其它函数
/*func simple(a func(a, b int) int) {
fmt.Println(a(10, 20))
}
func main() {
f := func(a, b int) int {
return a + b
}
simple(f)
}
//输出:30
*/
//实例2、在其它函数中返回函数
/*func simple() func(a, b int) int {
f := func(a, b int) int {
return a + b
}
return f
}
func main() {
s := simple()
fmt.Println(s(10, 20))
}
//输出:30
*/
//四、闭包
//闭包是匿名函数的一个特例,当一个匿名函数所访问的变量定义在函数体外部时,就称这样的匿名函数为闭包
//每一个闭包都会绑定一个它自己的外围变量
/*func appendStr() func(string) string {
t := "hello"
c := func(b string) string {
t = t + " " + b
return t
}
return c
}
func main() {
//下面声明的变量a, b都是闭包,他们绑定了各自的t 值
a := appendStr()
b := appendStr()
fmt.Println(a("world"))
fmt.Println(b("golang"))
fmt.Println(a("function"))
fmt.Println(b("!"))
}
//输出:
//hello world
//hello golang
//hello world function
//hello golang !
*/
//五、头等函数的实际用途
/*type student struct {
firstName string
lastname string
grade string
country string
}
//编写一个filter函数,这个函数计算一个student是否满足筛选条件
func filter(s []student, f func(student) bool) []student {
var r []student
//遍历student切片,将每个学生作为参数传给函数f
for _, v := range s {
if f(v) == true {
r = append(r, v)
}
}
return r
}
func main() {
s1 := student{
firstName: "tom",
lastname: "cat",
grade: "A",
country: "India",
}
s2 := student{
firstName: "jack",
lastname: "james",
grade: "B",
country: "USA",
}
//把s1 和s2添加到切片s
s := []student{s1, s2}
//查询所有成绩为B 的学生
f := filter(s, func(s student) bool {
if s.grade == "B" {
return true
}
return false
})
fmt.Println(f)
}
//输出:
// [{jack james B USA}]
*/
参考:Go 系列教程 —— 33. 函数是一等公民(头等函数)