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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊