blog icon indicating copy to clipboard operation
blog copied to clipboard

Go 语言个人随记

Open nkypy opened this issue 7 years ago • 0 comments

  • 并发安全,sync 包
var ipMap = struct {
	Lock sync.RWMutex
	Data map[string]string
}{Data: make(map[string]string)}
  • 循环中 defer 关闭,用 func() 包含
for _, v := range s {
	func() {
		ipMap.Lock.Lock()
		defer ipMap.Lock.Unlock()
		// 其他步骤
	}()
}
  • Json 数据处理,获取值
func jVal(key string, resp *http.Response) (val string) {
	var dat map[string]interface{}
	jData, err := ioutil.ReadAll(resp.Body)
	checkError(err)
	err = json.Unmarshal(jData, &dat)
	checkError(err)
	val = dat[key].(string)
	return val
}
  • 获取type
log.Println(reflect.TypeOf(resp))
  • 检查 map key, value 是否存在
if val, ok := dict["foo"]; ok {
    //do something here
}
  • 打印原格式数据
log.Printf("%#v", dat)
  • 时间戳字符串
time.Now().Unix()
  • string、int、int64互相转换
// string到int
int,err:=strconv.Atoi(string)
// string到int64
int64, err := strconv.ParseInt(string, 10, 64)
// 二进制字符串到十进制
int32, err := strconv.ParseInt(string, 2, 32)
// int到string
string:=strconv.Itoa(int)
// int64到string
string:=strconv.FormatInt(int64,10)
  • 创建及读写有名管道
//to create pipe: does not work in windows    
syscall.Mkfifo("tmpPipe", 0666)    

// to open pipe to write    
file, err1 := os.OpenFile("tmpPipe", os.O_RDWR, os.ModeNamedPipe)    

//to open pipe to read    
file, err := os.OpenFile("tmpPipe", os.O_RDONLY, os.ModeNamedPipe)
  • time.Sleep 问题
t := 5
time.Sleep(time.Second * 5) // ok 正常
time.Sleep(time.Second * t)  // error 出现错误提示 invalid operation: time.Second * t (mismatched types time.Duration and int)
time.Sleep(time.Second * time.Duration(t)) // ok 应该这样转
  • chan 类型作函数参数时, <- 符号的作用
// 起约束作用
out <-chan int // 只能出
in chan<- int // 只能进
  • 传递变长参数
func myFunc(a, b, arg ...int) {}
  • chan 数组
chList.BufRec[ip] = [2]chan []byte{
	make(chan []byte),
	make(chan []byte),
}
  • 文件文件夹检查及创建
if _, err := os.Stat(dir); os.IsNotExist(err) {
    os.Mkdir(dir, os.ModePerm)
}

if _, err := os.Stat(fn); os.IsNotExist(err) {
	os.OpenFile(fn, os.O_RDONLY|os.O_CREATE, 0644)
}
  • 获取绝对目录
dirRoot, err := filepath.Abs(filepath.Dir(os.Args[0]))
  • iota 自增长
const (
    _ = iota                        // iota = 0
    KB int64 = 1 << (10 * iota)    // iota = 1
    MB                             // 与 KB 表达式相同,但 iota = 2
    GB
    TB
)
  • Go 时间解析
时间点必须是 2006-01-02 15:04:05,无论何种格式
  • Go 使用 GitLab 私有仓库
export GOPRIVATE="gitlab.example.com"
git config --global url."[email protected]:".insteadOf "https://gitlab.example.com/"

nkypy avatar May 19 '17 10:05 nkypy