Golang的默认值模式

时间:2018-10-27 23:34:40

标签: go

我有这个:

port := os.Getenv("huru_api_port") ||  ":8000"

无法编译,如果huru_api_port为空/未定义,Golang不会将其识别为默认为“:8000”的语法。

有没有很好的方法可以做到这一点?附带说明一下,为什么用“:8000”而不是“ 8000”,例如:

log.Fatal(http.ListenAndServe(":8000", router))

3 个答案:

答案 0 :(得分:2)

在Go中没有简单的简便方法,但是对于您的情况,可以改用LookupEnv,它返回值(如果已设置)和一个布尔值,指示是否在环境中找到了密钥:

https://golang.org/pkg/os/#LookupEnv

答案 1 :(得分:2)

我会使用LookupEnv。它提供了boolean,如果未设置该变量,它将为false。

:8000意味着侦听器将绑定到所有网络接口。您可以认为它不同于127.0.0.1:8000,后者仅绑定到环回接口。

答案 2 :(得分:1)

os.LookupEnv将以字符串和布尔值的形式返回环境变量,该布尔值指示是否设置了该变量,因此您将得到

val abc1 = sc.textFile("hi.txt")
val abc2 = abc1.map {s =>

  // Split the string into tokens, delimited by a comma, put result in an array.
  val a = s.split(",")

  // Create a tuple of the expected values, converting the first value to an integer.
  (a(0).toInt, a(1), a(2))
}

使用方式:

v, ok = "something", true
// or, if the env var isn't set
v, ok = "", false
// or, if the env var is set but empty:
v, ok = "", true