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 ‘员’
- 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]]
}