一、switch语句:
1、switch之后可以不接条件表达式
2、case后条件表达式不限制于常量或整形,且可以有多个可选值。
3、case中的语句不需要写break来退出,但如果想继续执行下一个case需要用fallthrough关键字。
4、多个case公用一种处理
正确方式:
case A, B, C:
...
错误方式:
case A:
case B:
case C:
...

json:"val1"bson:"val2"json:",omitempty"json:"-"

三、http
res, err := http.Get(req.Url)
res.StatusCode

四、字符串
1、长度
在 Golang 中,如果字符串中出现中文字符不能直接调用 len 函数来统计字符串字符长度,这是因为在 [Go]中,字符串是以 UTF-8 为格式进行存储的,在字符串上调用 len 函数,取得的是字符串包含的 byte 的个数。
所以字符串长度需要通过len([]rune(str))来获取。
2、切割
golang字符串截取需要先将字符串转为切片,然后利用切片操作进行截取。
所以先进行这样的转换strs:=[]rune(stro),然后再通过sub:=strs[start:end](end大于等于start)进行截取,注意截取结果包含start不包含end。
3、与整型的转换
string转int:strconv.Atoi(string)
int转string:strconv.Itoa(int)
string转int64:strconv.ParseInt(string, 10, 64)
int64转string:strconv.FormatInt(int64,10)
4、正则
例如,一段内容中多个换行替换为一个换行,使得内容显示时没有空白行
regbr := regexp.MustCompile("(\r\n)+")
content = regbr.ReplaceAllString(content, "\r\n")

五、命令行
1、编译成指定命名的执行文件
go build -o xxxx main.go

六、time包
1、当前时间戳:
time.Now().Unix()
2、时间戳转格式化字符串:
time.Unix(1389058332, 0).Format("2006-01-02 15:04:05")
3、格式化字符串转时间戳:
the_time, _ := time.Parse("2006-01-02 15:04:05", datetime)
unix_time := the_time.Unix()
但是此方法转成的the_time是UTC时间,所以再用unix_time转成格式化字符串时,可能会与最开始传进来的datetime不一样。这种情况可以用另一个方法来解决:
the_time, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, time.Local)
unix_time := the_time.Unix()
4、获取当天0点0分0秒的时间戳
t:=time.Now() now:=time.Date(t.Year(),t.Month(),t.Day(),0,0,0,0,t.Location()).Unix()

七、iota
iota是golang语言的常量计数器,只能在常量的表达式中使用。
iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。
使用iota能简化定义,在定义枚举时很有用。
例如定义ErrorCode:
type ErrorCode int
const (
ParamError ErrorCode = iota + 1 // 1
DBError // 2
HttpError // 3
RpcError // 4
)

八、break label
我们在for多层嵌套时,有时候需要直接跳出所有嵌套循环, 这时候就可以用到go的label breaks特征了。
Exit:
for i := 0; i < 9; i++ {
for j := 0; j < 9; j++ {
if i+j > 15 {
fmt.Print("exit")
break Exit
}
}
}
break将直接退出两层循环。

十、数据结构
1、map类型中key如果有int是不能进行json序列化的
2、如果一个字段参数类型不固定,可将其声明为interface{}
3、float64类型转int或int64
var f float64 = 3.23
var i int = int(f)
var i64 int64 = int64(f)
4、float格式化输出
a:=strconv.FormatFloat(10.1,'f',2,64),输出10.10
a := strconv.FormatFloat(10.010, 'f', -1, 64),输出10.01

十一、make报错
1、clone下来tidb的代码以后,执行make,报错unrecognized import path "golang.org/x/tools/go/xxxx",解决办法:git clone https://github.com/golang/tools.git $GOPATH/src/golang.org/x/tools到本地后,重新make。