The use of anonymous functions in go language

  • 2020-06-23 00:40:01
  • OfStack


package main
import (
 "fmt"
 "go_code/chapter02/funinit/utils"
)
// 3 , global anonymous functions 
var(
 Fun1 = func(n1 int,n2 int) int {
 return n1 * n2
  }
)
// init  A function, usually in init Function to complete the initialization 
func main(){
 // 1 , when defining anonymous functions, which can only be called 1 time 
 res1 := func(n1 int,n2 int) int{
 return n1+n2
 }(10,20)
 fmt.Println("res1=",res1)
 // 2 , a  The data type of is the function type a  To complete the call 
 a := func(n1 int,n2 int) int{
 return n1 + n2
 }
 res2 := a(100,1000)
 fmt.Println("res2=",res2)
 res3 := Fun1(100,1000)
 fmt.Println("res3=",res3)
  fmt.Println("main......")
  fmt.Println("Age is value",utils.Age,"Name is value",utils.Name)
}

There's nothing to talk about, see one, get familiar with one:


package main
import (
 "fmt"
)
func main() {
 func() {
   fmt.Printf("func 1\n")
 }()
 func(x int) {
   fmt.Printf("func 2, x is %d\n", x)
 }(2)
 a := func(x int) int {
   fmt.Printf("func 3, x is %d\n", x)
   return 5
   }
 fmt.Println(a(3))
 fmt.Printf("%T\n", func() {
   fmt.Printf("func 1\n")
 })
 fmt.Printf("%T\n", func(x int) {
   fmt.Printf("func 2, x is %d\n", x)
 })
 fmt.Printf("%T\n", a)
}

Results:

[

func 1
func 2, x is 2
func 3, x is 3
5
func()
func(int)
func(int) int

]

Continue to look at:


package main
import (
  "fmt"
)
func main() {
  test(func(x string) {
   fmt.Println(x)
 })
}
func test(f func(string)) {
  f("hello")
}
[

Results: hello

]

But these are all wrong. Think about why:


package main
import (
 "fmt"
)
func main() {
 func() {
   fmt.Printf("func 1\n")
 }
}
package main
import (
  "fmt"
)
func main() {
  test(func g(x string) {
   fmt.Println(x)
 })
}
func test(f func(string)) {
  f("hello")
}

Finally, take a look at the following two correct programs:


package main
import (
  "fmt"
)
var x = "hello"
func main() {
  test(func (x *string) {
   *x = "world"
 })
 fmt.Println(x)
}
func test(f func(*string)) {
}
package main
import (
  "fmt"
)
func main() {
 var s1 = "hello"
 var s2 = "world"
  test(func(x *string, y *string) {
   *x += "_123"
   *y += "_456"
   }, &s1, &s2)
  fmt.Println(s1, s2) // hello_123 world_456
}
func test(f func(*string, *string), s1 *string, s2 *string) {
 f(s1, s2)
}
package main
import (
  "fmt"
)
var s1 = "hello"
var s2 = "world"
func main() {
  test(func(x *string, y *string) {
   *x += "_123"
   *y += "_456"
   })
  fmt.Println(s1, s2) // hello_123 world_456
}
func test(f func(*string, *string)) {
 f(&s1, &s2)
}

Not much said.

conclusion


Related articles: