vartest=func(){fmt.Println("The function is anonymous function")}funcmain(){test()fmt.Printf("test type: %v, %T\n",test,test)func(sstring){fmt.Println("The anonymous function test",s)}("arguments")}/*The function is anonymous functiontest type: 0x486eb0, func()The anonymous function test arguments*/
package main
import (
"fmt"
)
type add func(a int, b int) int
func main() {
var a add = func(a int, b int) int {
return a + b
}
s := a(5, 6)
fmt.Println("Sum", s)
}
// high order function use functions as arguments
func simple(a, b int, f func(c, d int) int) {
fmt.Println("result from function", f(a, b))
}
// high order functions use functions as return
func func_return(a int) func(int) int {
f := func(tmp int) int {
return a + tmp
}
return f
}
func main() {
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)
}
package main
import (
"fmt"
)
func appendStr() func(string) string {
t := "Hello"
c := func(b string) string {
t = t + " " + b
return t
}
return c
}
func main() {
a := appendStr()
b := appendStr()
fmt.Println(a("World"))
fmt.Println(b("Everyone"))
fmt.Println(a("Gopher"))
fmt.Println(b("!"))
}
package main
import (
"fmt"
)
type student struct {
firstName string
lastName string
grade string
country string
}
// filter all the students which make the `f` return true
func filter(s []student, f func(student) bool) []student {
var res []student
for _, v := range s {
if f(v) {
res = append(res, v)
}
}
return res
}
// impl iMap
func iMap(s []*student, f func(*student)) {
for _, v := range s {
f(v)
}
}
func main() {
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}
*/