Skip to content

Instantly share code, notes, and snippets.

View xin053's full-sized avatar
🎯
Focusing

xin053 xin053

🎯
Focusing
View GitHub Profile
@xin053
xin053 / select.go
Created July 5, 2019 06:35
[go select] go select #go #select
select {
case <-ch1:
//...
case x:= <-ch2:
//...
case ch3 <- y:
//...
default:
//...
}
@xin053
xin053 / test.md
Last active August 30, 2019 04:06
[go test] go test #go #test

Example

  • 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"
@xin053
xin053 / crypto_rand.go
Last active July 5, 2019 07:49
[go random]go random #go #random
// 更安全的随机
package main
import (
"crypto/rand"
// "encoding/base64"
// "encoding/hex"
"fmt"
)
@xin053
xin053 / interface.go
Last active July 5, 2019 09:41
[go interface{}] go interface{} #go #interface
// 故意在接口中定义方法, 以防止其他类型无意中实现了该接口
type runtime.Error interface {
error
RuntimeError()
}
// or
type testing.TB interface {
Error(args ...interface{})
Errorf(format string, args ...interface{})
@xin053
xin053 / slice.go
Last active July 7, 2019 07:42
[go slice] go slice #go #slice
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
}
@xin053
xin053 / singleton.go
Last active July 5, 2019 09:42
[go singleton] go singleton #go #singleton
// 通过 sync/Once 实现单例
var (
instance *singleton
once sync.Once
)
func Instance() *singleton {
once.Do(func() {
instance = &singleton{}
})
@xin053
xin053 / fmt.go
Created July 7, 2019 07:06
[go fmt] go fmt #go #fmt
// [Sp|Fp|P]rintf 支持位置参数
package main
import "fmt"
func main() {
fmt.Printf("%[3]v, %[2]v, %[1]v", 1, 2, 3) //3, 2, 1
}
@xin053
xin053 / time.go
Last active April 4, 2020 06:54
[go time] go time #go #time
// 获取指定月份的天数
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()
@xin053
xin053 / 类型断言.go
Last active July 7, 2019 07:51
[go 类型断言]go 类型断言 #go #类型断言
// 不通过反射, 通过类型断言判断一个类型是否含有某函数
package main
import (
"fmt"
)
type A int
type B int
@xin053
xin053 / string.go
Last active April 4, 2020 09:42
[go string] go string #go #string
// str[i] 取的是第 i 个 byte
package main
import (
"fmt"
)
func main() {
str1 := "abcdefg"
str2 := "测试"