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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵