如何避免在嵌套的if / else语句中两次写入else
语句?
func GetPortFromEnvironment(name string, defaultPort int32) int32 {
var port int32
if env := os.Getenv("SERVICE_PORT"); env != "" {
if _port, err := strconv.ParseInt(env, 10, 32); err != nil {
port = int32(_port)
} else {
port = defaultPort
}
} else {
port = defaultPort
}
return port
}
答案 0 :(得分:3)
如果其中包含可选语句,我会避免使用:
if statement; condition {
}
,并在以下情况下使用simple
:func GetPortFromEnvironment(name string, defaultPort int32) int32 {
env := os.Getenv("SERVICE_PORT")
// no env value. return defaultPort
if env == "" {
return defaultPort
}
// there's env value.
port, err := strconv.ParseInt(env, 10, 32)
if err != nil {
// Unable to parse port. Fallback to default.
return defaultPort
}
return int32(port)
}