package main import ( "fmt" "go_code/chapter02/funinit/utils" ) // 3. Global anonymous functionvar( Fun1 = func(n1 int,n2 int) int { return n1 * n2 } ) // init function, usually completes initialization work in init functionfunc main(){ // 1. Call it directly when defining anonymous functions. This method can only be called once. res1 := func(n1 int,n2 int) int{ return n1+n2 }(10,20) ("res1=",res1) // 2. The data type of a is the function type. At this time, we can complete the call through a a := func(n1 int,n2 int) int{ return n1 + n2 } res2 := a(100,1000) ("res2=",res2) res3 := Fun1(100,1000) ("res3=",res3) ("main......") ("Age is value",,"Name is value",) }
There is nothing to say, see one, and be familiar with one:
package main import ( "fmt" ) func main() { func() { ("func 1\n") }() func(x int) { ("func 2, x is %d\n", x) }(2) a := func(x int) int { ("func 3, x is %d\n", x) return 5 } (a(3)) ("%T\n", func() { ("func 1\n") }) ("%T\n", func(x int) { ("func 2, x is %d\n", x) }) ("%T\n", a) }
result:
func 1
func 2, x is 2
func 3, x is 3
5
func()
func(int)
func(int) int
Continue to watch:
package main import ( "fmt" ) func main() { test(func(x string) { (x) }) } func test(f func(string)) { f("hello") }
Results: hello
But the following are all wrong, think about why:
package main import ( "fmt" ) func main() { func() { ("func 1\n") } } package main import ( "fmt" ) func main() { test(func g(x string) { (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" }) (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) (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" }) (s1, s2) // hello_123 world_456 } func test(f func(*string, *string)) { f(&s1, &s2) }
Not to say much.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links