英文:
Golang constant 2d array syntax fails
问题
我想声明一个常量的二维数组(不是切片),但是我搞不清楚怎么做,我已经看了其他关于这个问题的Golang注释。
type fooT [1][1]float64
const BAR fooT = {[1]float64 {.01}}
会报错 fubar.go:5: syntax error: unexpected {
。但是下面的代码可以正常编译:
type fooT [1][1]float64
var BAR = fooT {[1]float64 {.01}}
首先,我不明白为什么我需要重复声明底层数组,而且似乎Golang编译器知道类型,因为如果我改变它会报错。但是,为什么我不能将这个数组声明为常量呢?它是只读的,不是全局的。
而且,这种语法很繁琐。
英文:
I want to declare a constant golang 2d array (not slices), but I can't figure it out, having looked at the other golang comments on this issue.
type fooT [1][1]float64
const BAR fooT = {[1]float64 {.01}}
Gives the error fubar.go:5: syntax error: unexpected {
. But the following compiles fine:
type fooT [1][1]float64
var BAR = fooT {[1]float64 {.01}}
First, I do not understand why I need to redeclare the underlying array redundantly, and it does seem golang compiler knows the type because it gives an error if I change it. But, why can I not make this array a const? it is R/O, not a global.
And, the syntax is cumbersome.
答案1
得分: 2
根据规范:
常量
Go语言中有布尔常量、符文常量、整数常量、浮点数常量、复数常量和字符串常量。
换句话说,在Go语言中不存在{结构体、数组、切片、映射、接口、指针}常量。
英文:
From the specs:
> Constants
>
> There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants.
IOW, in Go no {struct,array,slice,map,interface,pointer} constants exists.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论