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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘