Anonymous function hampir mirip function biasa, bedanya anonymous function bisa secara langsung di inisiasi ke suatu variabel.
Contoh code : anonymous function sebagai variabel
packagemainimport ("fmt")typeFilterfunc(name string) stringfuncsayHelloWithFilter(name string, filter Filter) { nameFiltered :=filter(name) fmt.Println("Hello", nameFiltered)}funcmain() {// anonymous function as variable filter :=func(name string) string {if name =="Kucing" {return"" } else {return name } }sayHelloWithFilter("Umar", filter)sayHelloWithFilter("Andi", filter)}
Hello Umar
Hello Andi
packagemainimport"fmt"var ( rectangle =func(p, l int) int {return p * l } triangle =func(a, t int) int {return a * t /2 })funcmain() { fmt.Println(rectangle(20, 30)) fmt.Println(triangle(20, 30))}
600
300
Contoh code 2 : anonymous function sebagai parameter
packagemainimport ("fmt")typeFilterfunc(name string) stringfuncsayHelloWithFilter(name string, filter Filter) { nameFiltered :=filter(name) fmt.Println("Hello", nameFiltered)}funcmain() {// anonymous function as parametersayHelloWithFilter("Umar", func(name string) string {if name =="Kucing" {return"" } else {return name } })sayHelloWithFilter("Andi", func(name string) string {if name =="Kucing" {return"" } else {return name } })}