Golang常量2D数组语法失败。

huangapple go评论90阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月31日 17:26:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/29365109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定