每当我们使用变量时,如何每次调用函数?

huangapple go评论87阅读模式
英文:

How to call func everytime when we use var

问题

你可以将代码重写如下,这样每次使用变量CsvVersion时,它都会调用函数并给出最新的值:

package main

import (
	"fmt"
	"os"
)

var (
	DefaultValMap = map[string]string{
		"CSV_VERSION": "v1",
	}

	CsvVersion = func() string {
		if val := os.Getenv("CSV_VERSION"); val != "" {
			return val
		}

		return DefaultValMap["CSV_VERSION"]
	}()
)

func main() {
	fmt.Println(CsvVersion)
	os.Setenv("CSV_VERSION", "v2")
	fmt.Println(CsvVersion)
	fmt.Println(os.Getenv("CSV_VERSION"))
}

实际输出应该如下所示:

$ go build 1.go && ./1 
v1
v2
v2
英文:

How I can rewrite the below code so that whenever I use the var CsvVersion every time it calls the func and gives me the latest value?

package main

import (
	"fmt"
	"os"
)

var (
	DefaultValMap = map[string]string{
		"CSV_VERSION": "v1",
	}

	CsvVersion = GetEnvOrDefault("CSV_VERSION")
)

func GetEnvOrDefault(env string) string {
	if val := os.Getenv(env); val != "" {
		return val
	}

	return DefaultValMap[env]
}

func main() {
	fmt.Println(CsvVersion)
	os.Setenv("CSV_VERSION", "v2")
	fmt.Println(CsvVersion)
	fmt.Println(os.Getenv("CSV_VERSION"))
}

Actual output

$ go build 1.go && ./1 
v1
v1
v2

The output should be like this

$ go build 1.go && ./1 
v1
v2
v2

答案1

得分: 8

在Go语言中,没有办法完全做到这一点。Go语言的设计非常避免使用类似这样的"魔法"操作。相反,不要使用变量,而是使用函数:

func CsvVersion() string {
    return GetEnvOrDefault("CSV_VERSION")
}

然而需要注意的是:在程序启动后(通常情况下)无法更改环境变量(除非在程序内部进行,但这种方式的效用非常有限),因此在每次使用时检查环境变量通常只是浪费功夫。可以在这里了解更多相关信息。

英文:

There is no way to do this exact thing in Go. Go, very much by design, avoids "magic" things like this. Instead, don't use a variable, use a function:

func CsvVersion() string {
    return GetEnvOrDefault("CSV_VERSION")
}

However note: It's not (generally) possible to change environment variables after a program starts (except within the program itself, which has very limited utility), so checking an env variable on every use is usually just wasted effort. Read more about that here.

huangapple
  • 本文由 发表于 2021年8月4日 18:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/68649437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定