是否可以在不同的文件中有兩個同名的常量?foo.goconst { deviceId = 1 // I dont need this outside the file scope}type DeviceA struct { .. some fields.. // I cannot make constant fields here}.. some methods ...bar.goconst { deviceId = 2 // I dont need this outside the file scope}type DeviceB struct { .. some fields .. // I cannot make constant fields here}.. some methods ...如果我這樣做,我會得到它deviceId已被重新聲明。如何將這些常量保留在文件的范圍內?如果可以解決這個問題,我不介意為常量使用某種命名空間。
2 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
回答你的問題:不可能有兩個具有相同名稱的常量,在相同的范圍內,在不同的文件中的相同包中。
Go 中沒有命名空間或文件范圍。
但是,在同一個包中可以有兩個同名的常量,但在不同的范圍內聲明:
package main
import (
"fmt"
)
const a = 1
func main() {
const a = 2
fmt.Println(a) // output is 2
}
scope 詳情請見:https://golang.org/ref/spec#Declarations_and_scope
- 2 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消