第一种写法
func (bus *es) PublicAll(topics []*EventTopic) {
for _, topic := range topics {
bus.mutex.Lock()
h, ok := bus.handlers[topic.Topic]
bus.mutex.Unlock()
if !ok {
continue
}
bus.client.Subscribe(topic.Topic, byte(topic.QoSValue), func(c mqtt.Client, m mqtt.Message) {
go func(h EventHandler) {
defer func() {
if err := recover(); err != nil {
fmt.Printf("goroutine panic: %+v \r\n", err)
}
}()
h(topic.Topic, m)
}(h)
})
}
}
第二种写法
func (bus *es) PublicAll(topics []*EventTopic) {
for _, topic := range topics {
bus.mutex.Lock()
h, ok := bus.handlers[topic.Topic]
bus.mutex.Unlock()
if !ok {
continue
}
go func(h EventHandler) {
defer func() {
if err := recover(); err != nil {
fmt.Printf("goroutine panic: %+v \r\n", err)
}
}()
bus.client.Subscribe(topic.Topic, byte(topic.QoSValue), func(c mqtt.Client, m mqtt.Message) {
h(topic.Topic, m)
})
}(h)
}
}
请问下上面两种写法,哪一种更好,为什么?除了以上方法还有其他更好的实现?感谢