duanqi6007 2018-08-16 13:50
浏览 27
已采纳

是否可以在不同的文件范围内重用常量名称?

Is it possible to have two constants with the same name in different files?

foo.go

const {
    deviceId = 1     // I dont need this outside the file scope
}

type DeviceA struct {
    .. some fields.. 
    // I cannot make constant fields here
}

.. some methods ...

bar.go

const {
    deviceId = 2      // I dont need this outside the file scope
}

type DeviceB struct {
    .. some fields ..
    // I cannot make constant fields here
}

.. some methods ...

If I do this, I get that deviceId has been redeclared. How can I keep these constants in the scope of the file?

I would not mind using some kind of namespace for the constants if that were a solution to this.

  • 写回答

2条回答 默认 最新

  • douhe4336 2018-08-16 14:13
    关注

    The Go Programming Language Specification

    Packages

    Go programs are constructed by linking together packages. A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package. Those elements may be exported and used in another package.

    Source file organization

    Each source file consists of a package clause defining the package to which it belongs, followed by a possibly empty set of import declarations that declare packages whose contents it wishes to use, followed by a possibly empty set of declarations of functions, types, variables, and constants.


    [constants] belonging to the package are accessible in all files of the same package.

    The fundamental Go compilation unit is the package. The source files in the package are merged to form the input to the compiler.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里