饿虎岗资源网 Design By www.oxmxm.com
package main import ( "fmt" "go_code/chapter02/funinit/utils" ) // 3、全局匿名函数 var( Fun1 = func(n1 int,n2 int) int { return n1 * n2 } ) // init 函数,通常在init函数中完成初始化工作 func main(){ // 1、在定义匿名函数时就直接调用,这种方式匿名函数只能调用一次 res1 := func(n1 int,n2 int) int{ return n1+n2 }(10,20) fmt.Println("res1=",res1) // 2、a 的数据类型就是函数类型,此时我们可以通过a 完成调用 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) }
没什么好说的, 见一个,熟悉一个:
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) }
结果:
func 1
func 2, x is 2
func 3, x is 3
5
func()
func(int)
func(int) int
继续看:
package main import ( "fmt" ) func main() { test(func(x string) { fmt.Println(x) }) } func test(f func(string)) { f("hello") }
结果:hello
但如下都错误, 想想为什么:
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") }
最后, 看看下面两个正确程序的:
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) }
不多说。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
饿虎岗资源网 Design By www.oxmxm.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
饿虎岗资源网 Design By www.oxmxm.com
暂无评论...
更新日志
2024年05月20日
2024年05月20日
- 张琍敏1978-雪中莲[台湾复刻版][WAV+CUE]
- 叶蕴仪1993-睡美人[日本版][WAV+CUE]
- 夜晚助兴音乐-群星《新时代床头音乐-性能量》2CD[WAV]
- 24K德国HD金碟《历届奥斯卡获奖金曲》3CD[WAV整轨]
- 邰正宵《重燃爱恋 贰 Walk On》[FLAC/分轨][431.72MB]
- 苏文劭《雨停出来走走》[320K/MP3][81.11MB]
- 苏文劭《雨停出来走走》[FLAC/分轨][210.76MB]
- 群星《2024好听新歌04》十倍音质WAV分轨
- 陈宁《弹指之间HQ》头版限量[低速原抓WAV+CUE]
- 陈宁《故人还》HQCDII限量签名版[低速原抓WAV+CUE]
- 苏文劭《春曲(Lessons)》[320K/MP3][39.8MB]
- 苏文劭《春曲(Lessons)》[FLAC/分轨][97.78MB]
- 群星《2006香港高级视听展原音精选 SACD》[ISO][2G]
- 张琍敏1977-枫林小雨[台湾复刻版][WAV+CUE]
- 林一峰2014-COOKINGMUSIC[香港首版][WAV+CUE]