我将避免使用包含可选语句的if:
if statement; condition {
}
</code>
并使用简单的if:
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)
}
</code>