gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:53:54 25 4
gpt4 key购买 nike

是否可以在不同的文件中有两个同名的常量?

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

酒吧去吧

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

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

.. some methods ...

如果我这样做,我会得到 deviceId 已被重新声明。如何将这些常量保留在文件范围内?

如果可以解决这个问题,我不介意为常量使用某种命名空间。

最佳答案

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.

Go 的基本编译单元是包。包中的源文件被合并以形成编译器的输入。

关于go - 是否可以在不同的文件范围内重用常量名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51878715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com