duanma8207 2018-04-11 14:10
浏览 1459
已采纳

在golang中的包之间共享常量

I’ve the following code which require multiple packages in cmd package

PATH_SEP = string(os.PathSeparator)

my project structure is like following

go/src/my proj
-cmd
--runners
--otherpackage
-- package2
-- constants
--…. 

in constants i put the code

PATH_SEP = string(os.PathSeparator)
const2 etc

and in runners and package2/3 etc I use this constant.

is it OK ? otherwise I need to duplicate the code for other packages .

  • 写回答

2条回答 默认 最新

  • duanan2732 2018-04-11 14:17
    关注

    I would suggest to declare struct with constant fields and import that struct in any package you wants to use the constants.

    package cmd
    type Constants struct{
        const1 int
        const2 int
    }
    

    It would be better to have a separate file for constants. Create a file called global.go which contains all constant structs to be used in different packages that way your code would be cleaner.

    Note: We require constants to be shared in multiple files, so it will be better to import the package containing constants. Rather than package containing methods and other details even if we do not need them.

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

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误