golang小记
2020-02-13 本文已影响0人
Dakini_Wind
- 深度拷贝map、struct
用json.unmarshal,变成字符串,然后再用 json.marshal生成新的map/struct - 拷贝interface
基于序列化和反序列化func deepCopy(dst, src interface{}) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(src); err != nil { return err } return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst) }
- 拷贝slice
预分配足够空间,然后用拷贝函数copyData := make([]int, elementCount) copy(copyData, srcData)
- 比较interface
先比较动态类型,再比较值;
或者 - 比较struct
reflect.DeepEqual - 为什么 go 能支持调度上百万个 goroutine ?调度器原理是什么?
协程,开销小 - 优雅关闭channel及判断
type MyChannel struct { C chan T closed bool mutex sync.Mutex } func NewMyChannel() *MyChannel { return &MyChannel{C: make(chan T)} } func (mc *MyChannel) SafeClose() { mc.mutex.Lock() defer mc.mutex.Unlock() if !mc.closed { close(mc.C) mc.closed = true } } func (mc *MyChannel) IsClosed() bool { mc.mutex.Lock() defer mc.mutex.Unlock() return mc.closed }
- 假如某一个 http 请求会有以下四个 goroutine 的调用链,如何通知这四个 goroutine 退出?有什么比较好的方案?
context包
当通过父Context对象创建子Context对象时,可同时获得子Context的一个撤销函数,这样父Context对象的创建环境就获得了对子Context将要被传递到的Goroutine的撤销权.
在子Context被传递到的goroutine中,应该对该子Context的Done信道(channel)进行监控,一旦该信道被关闭(即上层运行环境撤销了本goroutine的执行),应主动终止对当前请求信息的处理,释放资源并返回. - channel 和锁分别用在什么情况下?二者性能差异如何?
channel用于传数据,锁控制并发
锁的性能是channel的3倍左右 - struct{}场景
节省内存(map、channel)
封装