在golang中的包之间共享常量

在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 .

我有以下代码,它们需要 cmd code>包中的多个包 p>

  PATH_SEP = string(os.PathSeparator)
  code>  pre> 
 
 

我的项目结构如下 p> go / src / my proj -cmd --runners --otherpackage -- package2 -- constants --…。 code> pre>

在常量中,我将代码 p>

  PATH_SEP = string(os.PathSeparator)
const2等
   code>  pre> 
 
 

,并且在运行程序和package2 / 3等中使用此常量。 p>

可以吗? 否则,我需要复制其他软件包的代码。 p> div>

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.

You can use the constants as you describe, there is nothing wrong with it. But it is less intuitive.
How i would go about this is having a root package constants and those can be used anywhere in the project.

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