在 PHP 中我们可以这样做:
if ($env == "dev")
define("key", "key")
else
define("key", "secret")
// json ouput
//{ key : "value" } or { secret : "value" }
如何将上述 PHP 方法正确转换为 GO?
我在想这样的事情:
if *env == "dev" {
type response struct {
key string
...50 more keys that should also be different depending on env
}
} else {
secret string
...50 more keys...
}
但我想这不仅是错误的,而且还会产生巨大的重复代码...
最佳答案
您可以创建一个结构类型来保存您的数据结构的公共(public)部分,并且您可以创建新类型嵌入它并且只添加不同的新字段。所以没有数据结构公共(public)部分的代码重复:
type Response struct {
F1 string
F2 int
}
func main() {
for _, env := range []string{"dev", "prod"} {
if env == "dev" {
type Resp struct {
Response
Key string
}
r := Resp{Response{"f1dev", 1}, "value"}
json.NewEncoder(os.Stdout).Encode(r)
} else {
type Resp struct {
Response
Secret string
}
r := Resp{Response{"f1pro", 2}, "value"}
json.NewEncoder(os.Stdout).Encode(r)
}
}
}
输出(在 Go Playground 上尝试):
{"F1":"f1dev","F2":1,"Key":"value"}
{"F1":"f1pro","F2":2,"Secret":"value"}
请注意,如果 2 个用例的值相同,您也可以使用相同的 Response
值:
comResp := Response{"f1value", 1}
if env == "dev" {
type Resp struct {
Response
Key string
}
r := Resp{comResp, "value"}
json.NewEncoder(os.Stdout).Encode(r)
} else {
type Resp struct {
Response
Secret string
}
r := Resp{comResp, "value"}
json.NewEncoder(os.Stdout).Encode(r)
}
您可以通过使用匿名结构而不创建局部变量来缩短上面的代码(不一定更具可读性):
if env == "dev" {
json.NewEncoder(os.Stdout).Encode(struct {
Response
Key string
}{comResp, "value"})
} else {
json.NewEncoder(os.Stdout).Encode(struct {
Response
Secret string
}{comResp, "value"})
}
关于php - Golang 常量结构键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995236/