热烈欢迎你,相识是一种缘分,Echa 哥为了你的到来特意准备了一份惊喜,go学习资料《「转」go 语言实战笔记教程系列大纲汇总-值得收藏》
目录:
Go语言的那些坑
![ea9134e8eed16b4986338d5541e4a54c.png](https://i-blog.csdnimg.cn/blog_migrate/5c7d2191b9d48675225188441ed9a600.jpeg)
Golang中函数被看做是值,函数值不可以比较,也不可以作为map的key
请问以下代码能编译通过吗?
import ("fmt")func main(){array := make(map[int]func ()int)array[func()int{ return 10}()] = func()int{return 12}fmt.Println(array)}
答案:
可以正常编译通过。
稍作改动,改为如下的情况,还能编译通过吗?
import ("fmt")func main(){array := make(map[func ()int]int)array[func()int{return 12}] = 10fmt.Println(array)}
答案:
不能编译通过。
在Go语言中,函数被看做是第一类值:(first-class values):函数和其他值一样,可以被赋值,可以传递给函数,可以从函数返回。也可以被当做是一种“函数类型”。例如:有函数func square(n int) int { return n * n },那么就可以赋值f := square,而且还可以fmt.Println(f(3))(将打印出“9”)。Go语言函数有两点很特别:
- 函数值类型不能作为map的key
- 函数值之间不可以比较,函数值只可以和nil作比较,函数类型的零值是nil
匿名函数作用域陷阱
请看下列代码输出什么?
import ("fmt")func main(){var msgs []func()array := []string{"1", "2", "3", "4",}for _, e := range array{msgs = append(msgs, func(){fmt.Println(e)})}for _