官方学习路线
Go知识图谱
awesome-go
Go语言圣经(中文版)

string

注意:[]rune(str)开销是很大的。

  1. package main
  2. import "fmt"
  3. func main() {
  4. str := "z豪z"
  5. fmt.Printf("%s: len=%d, str[1]=%v\n", str, len(str), str[1])
  6. runes := []rune(str) // expensive conversion
  7. fmt.Printf("[]rune(%s): len=%d, str[1]=%d(%s)\n", str, len(runes), runes[1], string(runes[1]))
  8. }
  9. /*
  10. z豪z: len=5, str[1]=232
  11. []rune(z豪z): len=3, str[1]=35946(豪)
  12. */

自动解指针

这种情况是会输出hello的,会自动解指针。(也可能底层是自动生成一个属于指针的方法,方法里面解指针)

  1. package main
  2. type A struct {
  3. str string
  4. }
  5. func main(){
  6. a := &A{str:"hello"} // 换成 var a *A 会panic
  7. a.prt()
  8. }
  9. func (a A)prt(){ //注意这里
  10. println(a.str)
  11. }

Iota

https://my.oschina.net/renhc/blog/2906896
iota代表了const声明块的行索引(下标从0开始)

值传递

1

  1. 常量可以赋值给能表示它的自定义类型
  2. type不同不能赋值

    A value x is assignable to a variable of type T (“x is assignable to T”) if one of the following conditions applies: x’s type is identical to T. T is an interface type and x implements T. x is a bidirectional channel value, T is a channel type, x’s type V and T have identical element types, and at least one of V or T is not a defined type. x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type. x is an untyped constant representable by a value of type T.

若这样声明:

  1. var a *ListNodeB

这里是声明指针类型,不会初始化(分配内存空间)。所以a为指针类型,且a == nil。
而声明非指针类型就会初始化

  1. var a ListNodeB
  2. fmt.Println(a)结果为
  3. {0 <nil>}

所以声明过程相当于把里面的各个field逐一声明(内部指针仍为nil)

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type A struct {
  6. id uint32
  7. name string
  8. }
  9. func main() {
  10. a := new(A) // 等价于 a := &A{}
  11. fmt.Println(a)
  12. }

2

  1. type Elem struct {
  2. ID int
  3. Name string
  4. }
  5. func main() {
  6. var sli []Elem
  7. e := &Elem{
  8. ID: 1,
  9. Name: "A",
  10. }
  11. sli = append(sli, *e) // slice中的元素是一份拷贝
  12. e.Name += "+"
  13. fmt.Println(e)
  14. fmt.Println(sli)
  15. }
  16. 输出:
  17. &{1 A+}
  18. [{1 A}]

slice

元素为struct

  1. type Elem struct {
  2. ID int
  3. Name string
  4. }
  5. func main() {
  6. sli := []Elem{
  7. {
  8. ID: 1,
  9. Name: "A",
  10. },
  11. {
  12. ID: 2,
  13. Name: "B",
  14. },
  15. }
  16. p := &sli[0]
  17. fmt.Println(p)
  18. sli[0], sli[1] = sli[1], sli[0]
  19. fmt.Println(p)
  20. }
  21. 输出:
  22. &{1 A}
  23. &{2 B}

range

Go Range Loop Internals
实际实现:

  1. for_temp := range
  2. len_temp := len(for_temp)
  3. for index_temp = 0; index_temp < len_temp; index_temp++ {
  4. value_temp = for_temp[index_temp]
  5. index = index_temp
  6. value = value_temp
  7. original body
  8. }

如下删除slice中的所有偶数,为什么失败了?为什么 value=9 打印了3此?
因为前移一个元素时,后面超出长度的位置的内存数据是不变的。

  1. func main() {
  2. sli := []int{4,2,2,3,9}
  3. for i, v := range sli {
  4. fmt.Printf("transverse index=%d, value=%d\n", i,v )
  5. if v % 2 == 0 {
  6. sli = append(sli[:i], sli[i+1:]...)
  7. fmt.Printf("after remove: %v\n", sli)
  8. }
  9. }
  10. fmt.Println("result", sli)
  11. }
  12. 输出:
  13. transverse index=0, value=4
  14. after remove: [2 2 3 9]
  15. transverse index=1, value=2
  16. after remove: [2 3 9]
  17. transverse index=2, value=9
  18. transverse index=3, value=9
  19. transverse index=4, value=9
  20. result [2 3 9]

正确实现是:

  1. func main() {
  2. sli := []int{1,4,2,2,3,9,6}
  3. for i := 0; i < len(sli); {
  4. if sli[i] % 2 == 1 {
  5. i++
  6. continue
  7. }
  8. sli = append(sli[:i], sli[i+1:]...)
  9. }
  10. fmt.Println("result", sli)
  11. }
  12. 输出:
  13. result [1 3 9]
  1. func main() {
  2. sli := []int{4,2,2,3,9}
  3. for i, v := range sli {
  4. fmt.Printf("transverse index=%d, value=%d\n", i,v )
  5. sli = nil
  6. }
  7. fmt.Println("result", sli)
  8. }
  9. 输出:
  10. transverse index=0, value=4
  11. transverse index=1, value=2
  12. transverse index=2, value=2
  13. transverse index=3, value=3
  14. transverse index=4, value=9
  15. result []
  1. func main() {
  2. sli := []int{4,2,2,3,9}
  3. for i, v := range sli {
  4. fmt.Printf("transverse index=%d, value=%d\n", i,v )
  5. sli = []int{7,7,7}
  6. }
  7. fmt.Println("result", sli)
  8. }
  9. 输出:
  10. transverse index=0, value=4
  11. transverse index=1, value=2
  12. transverse index=2, value=2
  13. transverse index=3, value=3
  14. transverse index=4, value=9
  15. result [7 7 7]

所以,range slice时,不要改变切片长度。

而 range map时,插入元素也会有问题,后续遍历可能会遇到新插入元素,也可能不会。因为 Go map 是链式哈希表,我猜插入到当前遍历位置后边就可以遇到这个新元素。删除元素则没有问题。

map

a way to allocate hash-map lazily

  1. type kvMap map[string]string
  2. func (pm *kvMap) insert(key, val string) {
  3. if *pm == nil {
  4. *pm = make(kvMap)
  5. }
  6. (*pm)[key] = val
  7. }
  8. func main() {
  9. var kv kvMap
  10. kv.insert("a", "A")
  11. fmt.Println("result", kv)
  12. }
  13. 输出:
  14. result map[a:A]

GC

Golang 垃圾回收剖析

Context

学习资源:
Package context

Go Concurrency Patterns: Context

Go语言实战笔记(二十)| Go Context - 飞雪无情

  • 什么是WaitGroup
  • chan通知
  • 初识Context
  • Context控制多个goroutine
  • Context接口
  • Context的继承衍生
  • WithValue传递元数据
  • Context 使用原则

如何在 Go 中正确使用 context.Context

How to correctly use context.Context in Go 1.7

Channel

注意:关闭管道只是为了不再往里面传数据,为防止数据丢失,管道仍然可以取出数据。若管道关闭则取出来的数据为对应默认值。所以管道关闭后管道指针值仍然没变。

  1. chan 必须用make创建,否则变量为空引用,往该管道传入/传出数据会永久堵塞。
  2. channel若关闭了,管道仍然可以给变量赋值,为默认值。(防止管道关闭后管道里面的数据丢失)
  3. 管道关闭后给channel赋值会panic。
  4. 重复关闭channel会panic。
  5. 管道关闭后channel != nil
  1. func main(){
  2. ch := make(chan int)
  3. var a int
  4. go func(){
  5. ch <- 1
  6. close(ch)
  7. }()
  8. for true {
  9. select {
  10. case a = <-ch:
  11. fmt.Println(a)
  12. fmt.Println(ch)
  13. }
  14. time.Sleep(1*time.Second)
  15. }
  16. }
  17. 输出:
  18. 1
  19. 0xc420078060
  20. 0
  21. 0xc420078060
  22. 0
  23. 0xc420078060

例子:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main(){
  7. ch := make(chan struct{})
  8. go func(){
  9. fmt.Println("get signal from channal:",<-ch)
  10. }()
  11. time.Sleep(1e9)
  12. close(ch)
  13. time.Sleep(1e9)
  14. }
  15. 输出:
  16. get signal from channal: {}

Go: Broadcast channels?

工具链

go build

编译出可执行文件,可执行文件放在当前目录下

go install

编译出可执行文件,可执行文件放到GOPATH/bin目录下(当有多个gopath的时候使用第一个)

go get

git clone + go install
go1.10出现了一个新的环境变量叫做$GOTMPDIR,go install 和go build会把编译过的依赖缓存到这个目录下。(以前是用的$gopath/pkg实现类似功能)如果未设置$GOTMPDIR,则使用系统默认的文件缓存目录。
参考:
go install vs go build
go-command-tutorial

go tool compile

查看汇编代码:

  1. go tool compile -S file

并发编程

Go Concurrency Patterns - Rob Pike
并发原语go、channel、select介绍。以及搭配for range、值为nil的channel
Example: Google Search

Codewalk: Share Memory By Communicating
轮询一堆url以更新url的状态,隔一段时间打印所有url的状态。

Go Concurrency Patterns: Timing out, moving on

Advanced Go Concurrency Patterns - Sameer Ajmani
实现一个feed reader的服务端

Go Concurrency Patterns: Pipelines and cancellation - Sameer Ajmani

Go Concurrency Patterns: Context - Sameer Ajmani

类型系统

https://sanyuesha.com/2017/07/27/go-type/

代码风格

【译】Go 语言实践:编写可维护的程序的建议

Panic栈信息

  1. 开发阶段尽可能panic()来快速定位bug的位置。
  2. 如果不想中止程序。用debug.PrintStack()替代panic()
  1. import (
  2. "runtime/debug"
  3. )
  4. func main() {
  5. Example(true, false, true, 25)
  6. }
  7. func Example(b1, b2, b3 bool, i uint8) {
  8. debug.PrintStack()
  9. }

理解这一点的关键是要知道每个参数类型的实现机制。
比如当参数是slice,则会看到传入参数为指针、长度、容量。当有reciver,且是指针,则第一个参数是reciver。注意string是一个指针、一个长度实现的。
但是有特殊情况:

  1. import (
  2. "runtime/debug"
  3. )
  4. func main() {
  5. Example(true, false, true, 25)
  6. }
  7. func Example(b1, b2, b3 bool, i uint8) {
  8. debug.PrintStack()
  9. }
  1. goroutine 1 [running]:
  2. runtime/debug.Stack(0x4, 0xc00007a010, 0xc000077f88)
  3. C:/Go/src/runtime/debug/stack.go:24 +0xae
  4. runtime/debug.PrintStack()
  5. C:/Go/src/runtime/debug/stack.go:16 +0x29
  6. main.Example(0xc019010001)
  7. D:/gopath/src/example/example/main.go:12 +0x27
  8. main.main()
  9. D:/gopath/src/example/example/main.go:8 +0x30

这是因为bool类型与uint8都是占一个字节,这里被打包(packing)成为0xc019010001了。

  1. // Parameter values
  2. true, false, true, 25
  3. // Word value
  4. Bits Binary Hex Value
  5. 00-07 0000 0001 01 true
  6. 08-15 0000 0000 00 false
  7. 16-23 0000 0001 01 true
  8. 24-31 0001 1001 19 25
  9. // Declaration
  10. main.Example(b1, b2, b3 bool, i uint8)
  11. // Stack trace
  12. main.Example(0x19010001)

参考:
如何理解打印出来的stack trace的参数?
https://www.ardanlabs.com/blog/2015/01/stack-traces-in-go.html