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中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂