drgc9632 2019-08-25 08:44
浏览 300
已采纳

如何在Go中创建键值的枚举/映射

I am new to Go and love it so far but it seems that I cannot find a simple solution to this.

I want to create a constant that I can reference in my code by Key and get its value

I have this:

const (
    DBName            = "goApi"
    UsersTable string = "users"
)

And would like to have a Tables constant variable that stores the value

Example:

var Tables = {
   UsersTable : "users",
   PostsTable : "posts"
}

//Somewhere else in the code
fmt.Println(Tables.UsersTable) //output "users"

How can I achieve this in Go?

  • 写回答

2条回答 默认 最新

  • du532861657 2019-08-25 11:52
    关注

    What you can declare as const in Go is limited to only the basic types like ints, strings, bools, etc. There is no way to declare non-basic types like structs, maps, slices, funcs, etc. as a const.

    So to get to Tables.UsersTable you can either declare your Tables as a struct var:

    var Tables = struct{
        UsersTable string
        PostsTable string
    }{
        UsersTable: "users",
        PostsTable: "posts",
    }
    

    Note that since this is a variable and not a constant, there's nothing that protects the fields' values from being modified by malice or bug.

    Or, the other option you have is to create a new package, name it tables, and in it declare your constants.

    package tables
    
    const (
        UsersTable = "users"
        PostsTable = "posts"
    )
    

    Then you can use it by simply importing the package

    import (
        "fmt"
        "path/to/tables"
    )
    
    func main() {
        fmt.Println(tables.UsersTable)
    }
    

    Note that the first solution, if imported by another package will result in fmt.Println(somepkg.Tables.UsersTable) (unless a . import is used) which may not be what you're looking for, or maybe it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题