var test =func() { fmt.Println("The function is anonymous function")}funcmain() {test() fmt.Printf("test type: %v, %T\n", test, test)func (s string) { fmt.Println("The anonymous function test", s) }("arguments")}/*The function is anonymous functiontest type: 0x486eb0, func()The anonymous function test arguments*/
packagemainimport ( "fmt")typeaddfunc(a int, b int) intfuncmain() { var a add=func(a int, b int) int {return a + b } s :=a(5, 6) fmt.Println("Sum", s)}
1.2 高阶函数
高阶函数是指使用了函数作为参数或者返回值的函数,这是firstclass函数的一种基础的使用方式:
// high order function use functions as argumentsfuncsimple(a, b int, f func(c, d int) int) { fmt.Println("result from function", f(a, b))}// high order functions use functions as returnfuncfunc_return(a int) func(int) int { f :=func(tmp int) int {return a + tmp }return f}funcmain() { fmt.Println("Usage of high order functions")simple(1, 2, func(c, d int) int {return c * d }) res :=func_return(2)(1) fmt.Println("result from the returned function", res)}
packagemainimport ( "fmt")funcappendStr() func(string) string { t :="Hello" c :=func(b string) string { t = t +" "+ breturn t }return c}funcmain() { a :=appendStr() b :=appendStr() fmt.Println(a("World")) fmt.Println(b("Everyone")) fmt.Println(a("Gopher")) fmt.Println(b("!"))}
在以上代码中,分别使用a,b两个变量作为两个实现相同的函数,每i一个函数具有自己独立的闭包。
3. 典型使用场景
first class function通常用于需要对于一批对象进行批处理,比如进行检索,进行函数的映射。使用这种函数可以得到更为简洁的代码。以下面的代码为例,需要检索所有满足参数函数的条件对象:
packagemainimport ("fmt")typestudentstruct { firstName string lastName string grade string country string}// filter all the students which make the `f` return truefuncfilter(s []student, f func(student) bool) []student {var res []studentfor _, v :=range s {iff(v) { res =append(res, v) } }return res}// impl iMapfunciMap(s []*student, f func(*student)) {for _, v :=range s {f(v) }}funcmain() { s1 := student {"Nikofl","Inno","B","Japan", } s2 :=student{"James","Leborn","A","America", } s3 := student {"Kiturl","Deropmerl","B","Greek", } students := []student{s1, s2, s3} set :=filter(students, func(s student) bool {return s.grade =="B" }) fmt.Println("All the students whose grade is B\n", set) sets := []*student{&s1, &s2, &s3} fmt.Println("Now every students' grade should be upgrade")iMap(sets, func(s *student) { (*s).grade +="+" })for _, v :=range sets { fmt.Println(*v) }}/*All the students whose grade is B [{Nikofl Inno B Japan} {Kiturl Deropmerl B Greek}]Now every students' grade should be upgrade{Nikofl Inno B+ Japan}{James Leborn A+ America}{Kiturl Deropmerl B+ Greek}*/