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 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线