Golang编程技巧

Golang编程技巧

数组、切片、字符串截取
截取的新变量与就变量共用一个数组结构,不需要额外分配。

1
2
a := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
a1 := a[1,3] // a1 = [2,3]

使用`创建避免转义

使用字节数组或缓冲区可以提升字符串连接的速度
在 Go 语言中字符串是只读的,这表示每次当你使用 str = str + "something" 时,实际上创建了一个新的字符串对象。如果你寻求代码的最高效率,这里应该使用字节缓冲区来替代,例如:

1
2
3
4
5
6
str := "something"
buf := bytes.NewBufferString(str)
for i := 0; i < 1000; i++ {
buf.Write([]byte(randomString()))
}
fmt.Println(buf.String())

显式标识结构实现的接口

  • 直观表现实现的接口
  • 编译时候能够检查是否有遗漏实现
  • 接口方法变化后也能很快地检查出来
1
2
3
4
5
6
7
8
9
type VolumePlugin interface {
...
}

type rbdPlugin struct {
...
}

var _ VolumePlugin = &rbdPlugin{} // 检查rbdPlugin是否实现了VolumePlugin接口

空结构体的妙用
空结构体struct{}占用0的空间。在只作为信号通知的通道中,可以定义空结构体的通道

1
2
ch := make(chan struct{})
ch <- struct{}{}

Sets实现

golang的基本数据结构中并没有Set结构,但是可以使用map来实现。

1
2
3
type HashSet map[interface{}]bool

type HashSet map[interface{}]struct{}

http打桩

httptest包中提供了HTTP的桩函数。

1
2
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
显示 Gitment 评论