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

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.

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.

To answer your question: It is not possible to have two constants with the same name, in the same scope, the same package in separated files.

There is no namespace or file scope in Go.

However, it is possible to have two constants of the same name in the same package but declared at different scope:

package main

import (
    "fmt"
)

const a = 1

func main() {
    const a = 2
    fmt.Println(a) // output is 2
}

For details of scope, please see: https://golang.org/ref/spec#Declarations_and_scope