一篇速记
1. go中的slice特性
首先知道slice是[指向数组的指针,len, cap]这个三元组构成的,然后看下面的两个例子。
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// 截取切片使其长度为 0
y := s[:1]
printSlice(y)
y[0] = 100
printSlice(s)
y = append(y, 101)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
输出如下
len=6 cap=6 [2 3 5 7 11 13]
len=1 cap=6 [2]
len=6 cap=6 [100 3 5 7 11 13]
len=6 cap=6 [100 101 5 7 11 13]
主要想强调的是一个局部的slice引用的append会覆盖数组中对应的下一个元素。
第二个例子:
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// 截取切片使其长度为 0
y := s[:1]
printSlice(y)
s = append(s, 0)
y[0] = 100
printSlice(s)
y = append(y, 101)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
输出
len=6 cap=6 [2 3 5 7 11 13]
len=1 cap=6 [2]
len=7 cap=12 [2 3 5 7 11 13 0]
len=7 cap=12 [2 3 5 7 11 13 0]
这里的例子想强调的是append导致扩容,数组复制时会使得其它的slice与append的返回值解绑(对比上一个例子,这个例子中修改y无法影响新的s),事实上此时内存中就有两个数组了。
2. 同一模块的本地package导入
Package Name and Directory/Folder Name in Go (Golang)- Does they need to be the same
这篇链接可阐述得太好了,想强调的一点就是在语义上
import "xyz.com/abc/sample"
这是导入了package所在的目录,当然通常sample目录下一般就是
package sample
,如果下面是package hello
,那么实际调用hello包的函数HHH
就应该写为
import "xyz.com/abc/sample"
hello.HHH()
嗯,看着确实挺奇怪的。