range使用注意

1. 对字符串的遍历按照Unicode而不是byte

package main

import "log"

func main() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
	str := "程序员"
	for i, rune := range str {
		log.Printf("%v %q\n", i, rune)
	}
}

输出:

0 ‘程’
3 ‘序’
6 ‘员’

  1. range在slice和map上迭代,并返回index,value时,其中的value是迭代对象中的元素副本,而不是指向副本的指针。
//log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
package main

import (
	"log"
	"reflect"
	"unsafe"
)

func main() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
	items := make([][]int, 10)
	for i, tmp := range items {
		log.Printf("items[%v] underlying fields addr:%+v| tmp underlying fields addr:%+v| tmp addr:%p\n",
			i, *(*reflect.SliceHeader)(unsafe.Pointer(&items[i])), *(*reflect.SliceHeader)(unsafe.Pointer(&tmp)), &tmp)
		tmp = make([]int, 1)
		tmp[0] = 2
		log.Printf("after assignment items[%v] underlying fields addr:%+v| tmp underlying fields addr:%+v| tmp addr:%p\n",
			i, *(*reflect.SliceHeader)(unsafe.Pointer(&items[i])), *(*reflect.SliceHeader)(unsafe.Pointer(&tmp)), &tmp)
	}
	log.Printf("%+v\n", items)// [[] [] [] [] [] [] [] [] [] []]
}

package main

import (
	"log"
)

func main() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
	items := make([][]int, 10)
	for i := range items {
		items[i] = make([]int, 1)
		items[i][0] = 2
	}
	log.Printf("%+v\n", items)//[[2] [2] [2] [2] [2] [2] [2] [2] [2] [2]]
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值