下面的代码是死循环么?
func main() {
v := []int{1, 2, 3}
for i := range v {
v = append(v, i)
}
}
sliceslicevfor
v[0, 1, 2]for range
语法糖
语法糖(Syntactic
sugar),也译为糖衣语法,是由英国计算机科学家彼得·蘭丁发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能没有影响,但是更方便程序员使用。
语法糖让程序更加简洁,有更高的可读性。
for range
// for_temp := range
// len_temp := len(for_temp)
// for index_temp = 0; index_temp < len_temp; index_temp++ {
// value_temp = for_temp[index_temp]
// index = index_temp
// value = value_temp
// original body
// }
len_temp := len(for_temp)
下面的代码有什么问题么?
slice := []int{0, 1, 2, 3}
myMap := make(map[int]*int)
for index, value := range slice {
fmt.Println(&index, &value)
myMap[index] = &value
}
fmt.Println("=====new map=====")
for k, v := range myMap {
fmt.Printf("%d => %d\n", k, *v)
}
myMap
== ===new map=====
0 => 3
1 => 3
2 => 3
3 => 3
valuevaluemyMapvaluemyMapvalue
value
切片For Range原理
index
其它语法糖
另外,For Range 不光支持切片。其它的语法糖底层代码。
map
// Lower a for range over a map.
// The loop we generate:
// var hiter map_iteration_struct
// for mapiterinit(type, range, &hiter); hiter.key != nil; mapiternext(&hiter) {
// index_temp = *hiter.key
// value_temp = *hiter.val
// index = index_temp
// value = value_temp
// original body
// }
channel
// Lower a for range over a channel.
// The loop we generate:
// for {
// index_temp, ok_temp = <-range
// if !ok_temp {
// break
// }
// index = index_temp
// original body
// }
数组
// Lower a for range over an array.
// The loop we generate:
// len_temp := len(range)
// range_temp := range
// for index_temp = 0; index_temp < len_temp; index_temp++ {
// value_temp = range_temp[index_temp]
// index = index_temp
// value = value_temp
// original body
// }
字符串
// Lower a for range over a string.
// The loop we generate:
// len_temp := len(range)
// var next_index_temp int
// for index_temp = 0; index_temp < len_temp; index_temp = next_index_temp {
// value_temp = rune(range[index_temp])
// if value_temp < utf8.RuneSelf {
// next_index_temp = index_temp + 1
// } else {
// value_temp, next_index_temp = decoderune(range, index_temp)
// }
// index = index_temp
// value = value_temp
// // original body
// }