php - Golang 常量结构键

标签 php json data-structures go

在 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/

相关文章:

php - 如何对多维数组进行urlencode?

arrays - Swift 中的字典数组

java - 树的分区压缩以及如何将节点压缩到根

javascript - 发布和从服务器获取

arrays - 给定列车时刻表所需的最少站台数量

java - 嵌入式设备上的静态数据结构(尤其是 Android)

php - 如何在 php 页面加载时将下拉选择的值存储在变量中?

php - 附加位置字段

php - 如何用字母在前,符号在后对 MySQL 结果进行排序?

javascript - 计算后将JSON对象值转为十进制数