Go os Getenv LookupEnv 的区分

5 min read
// Getenv retrieves the value of the environment variable named by the key.
// It returns the value, which will be empty if the variable is not present.
// To distinguish between an empty value and an unset value, use LookupEnv.
func Getenv(key string) string {
   testlog.Getenv(key)
   v, _ := syscall.Getenv(key)
   return v
}

// LookupEnv retrieves the value of the environment variable named
// by the key. If the variable is present in the environment the
// value (which may be empty) is returned and the boolean is true.
// Otherwise the returned value will be empty and the boolean will
// be false.
func LookupEnv(key string) (string, bool) {
   testlog.Getenv(key)
   return syscall.Getenv(key)
}

os.Getenv 和 os.LookupEnv 用于获取环境变量值。os.Getenv 会返回环境变量的值,如果找不到,则返回空字符串。而 os.LookupEnv 只会返回环境变量的值,如果找不到,则返回 ok 为 false,而不是返回空字符串。