Skip to content
李小明 edited this page Dec 15, 2022 · 40 revisions

基础

指南 https://tour.go-zh.org/list

数组

长度不定:

var userNameArray []string
userNameArray = append(userNameArray, "小明")
userNameArray = append(userNameArray, "小红")

长度来自变量:

n := 3
data := make([]byte, n)

map

创建:

m := make(map[string]bool)
m["小明"] = true
m["小红"] = false
log.Println(m)

判断键是否存在:

if v, exists := m["小明"]; exists {
  log.Println(v);
}

删除:

delete(m, "小明")

参考 https://tour.go-zh.org/moretypes/22

伪Set

s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element 
delete(s, 2) // remove element

参考 https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure

range遍历

//数组
as := []string{"a","b"}
for index, value := range as {
  fmt.Println(index, value)
}

//map
kvs := map[string]string{"a": "apple", "b": "banana"}
for key, value := range kvs {
  fmt.Println(key, value)
}

参考 https://gobyexample.com/range

执行bash

	cmd := "git version"
	out, err := exec.Command("bash", "-c", cmd).CombinedOutput()
	if err != nil {
		log.Fatalf("执行失败: %s\n", err)
	}
	version := string(out)
	log.Println(version)

Go Kafka

库网址

安装依赖

下载v1.3.0, 解压并进入文件夹内执行:

$ sudo apt install -y make pkg-config libssl-dev
$ ./configure --reconfigure --prefix=/usr/local --enable-lz4-ext --install-deps
$ make -j32
$ sudo make install

有时直接使用报错, 此时可以安装 librdkafka-dev 然后马上把它卸载. 再执行make install就好了. 不要使用1.4以上版本, 无法静态构建问题.

启用SSL文档, 确认打印信息中有WITH_SSL y.

Go WebSocket

使用https://github.com/gorilla/websocket

Go Redis

使用https://github.com/go-redis/redis

Go Postgres

使用https://github.com/lib/pq

Go Expression(表达式,如3 > 2是否为真)

使用https://github.com/Knetic/govaluate

$ go get github.com/Knetic/govaluate