Go语言中的"短变量声明 + 错误检查"模式详解
基础语法结构:
if err := someFunction(); err != nil {
// 处理错误的代码
}
以下面的代码为例:
if err := gm.sendSubscription(ctx, conn, group.ReaderCfg.Subs); err != nil {
log.Printf("Group %s: Failed to send subscription: %v", group.Name, err)
conn.Close(websocket.StatusInternalError, "subscription failed")
continue
}
上面的代码翻译一下就是:
err := gm.sendSubscription(ctx, conn, group.ReaderCfg.Subs)
if err!=nil{
log.Printf("Group %s: Failed to send subscription: %v", group.Name, err)
conn.Close(websocket.StatusInternalError, "subscription failed")
continue
}
示例中的err和err != nil是同一个变量。让处理错误更加简洁,这种是golang独有的内联写法
// 文件操作
if file, err := os.Open("file.txt"); err != nil {
// 处理错误
} else {
// 使用file
defer file.Close()
}