版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/scylhy/article/details/88680705
- for-range
package main
import "fmt"
func main() {
slice := []int{0, 1, 2, 3}
mp := make(map[int]*int)
fmt.Println("for range 坑")
for index, value := range slice {
mp[index] = &value
}
//根本原因在于for range是用一个变量承接mp中的内容的
for key, value := range mp {
fmt.Println(key, " ", *value)
}
fmt.Println("等价写法")
var index, value int
mp2 := make(map[int]*int)
for index, value = range slice {
mp2[index] = &value
}
for key, value := range mp2 {
fmt.Println(key, " ", *value)
}
fmt.Println("正确写法")
mp3 := make(map[int]*int)
for index, value := range slice {
num := value
mp3[index] = &num
}
//根本原因在于for range是用一个变量承接mp中的内容的
for key, value := range mp3 {
fmt.Println(key, " ", *value)
}
}
输出:
for range 坑
0 3
1 3
2 3
3 3
等价写法
0 3
1 3
2 3
3 3
正确写法
0 0
1 1
2 2
3 3
有疑问加站长微信联系(非本文作者)