- It needs to be in a file with a name like
xxx_test.go - The test function must start with the word
Test - The test function takes one argument only
t *testing.T
package main
import "testing"| select { | |
| case <-ch1: | |
| //... | |
| case x:= <-ch2: | |
| //... | |
| case ch3 <- y: | |
| //... | |
| default: | |
| //... | |
| } |
| // 更安全的随机 | |
| package main | |
| import ( | |
| "crypto/rand" | |
| // "encoding/base64" | |
| // "encoding/hex" | |
| "fmt" | |
| ) |
| // 故意在接口中定义方法, 以防止其他类型无意中实现了该接口 | |
| type runtime.Error interface { | |
| error | |
| RuntimeError() | |
| } | |
| // or | |
| type testing.TB interface { | |
| Error(args ...interface{}) | |
| Errorf(format string, args ...interface{}) |
| func TrimSpace(s []byte) []byte { | |
| b := s[:0] // 0 长度切片, len 虽然是0, 但是 cap 不为 0 | |
| for _, x := range s { | |
| if X != ' ' { | |
| b = append(b, x) | |
| } | |
| } | |
| return b | |
| } |
| // 通过 sync/Once 实现单例 | |
| var ( | |
| instance *singleton | |
| once sync.Once | |
| ) | |
| func Instance() *singleton { | |
| once.Do(func() { | |
| instance = &singleton{} | |
| }) |
| // [Sp|Fp|P]rintf 支持位置参数 | |
| package main | |
| import "fmt" | |
| func main() { | |
| fmt.Printf("%[3]v, %[2]v, %[1]v", 1, 2, 3) //3, 2, 1 | |
| } |
| // 获取指定月份的天数 | |
| package main | |
| import ( | |
| "fmt" | |
| "time" | |
| ) | |
| func days(year int, month time.Month) int { | |
| return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day() |
| // 不通过反射, 通过类型断言判断一个类型是否含有某函数 | |
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type A int | |
| type B int |
| // str[i] 取的是第 i 个 byte | |
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| func main() { | |
| str1 := "abcdefg" | |
| str2 := "测试" |