这个问题在这里已经有了答案:
Initialize const variable
(1 个回答)
2年前关闭。
我使用 go playground 来尝试这段代码:
package main
func main() {
exp := []string{"HELLO"}
const length = len(exp)
}
但它给了我这个错误:
./prog.go:6:8: const initializer len(exp) is not a constant
我可以看到这种情况正在发生,因为 exp 的长度是可变的。如何获取当前长度并将其存储在整数常量中?
我认为我需要反射模块来执行此操作,但我不知道该怎么做。我尝试使用
reflect.ValueOf
但它没有用。exp := []string{"HELLO"}
const length = len(reflect.ValueOf(exp).Interface().([]string))
最佳答案
您确实可以获得当前长度,但根据定义,这不是一个常数。 Here is what the language specification has to say about this :
The expression
len(s)
is constant ifs
is a string constant. The expressionslen(s)
andcap(s)
are constants if the type ofs
is an array or pointer to an array and the expressions
does not contain channel receives or (non-constant) function calls; in this cases
is not evaluated. Otherwise, invocations oflen
andcap
are not constant ands
is evaluated.
自从您调用
len
为 len(exp)
我们必须测试exp
针对上面的文字:len
的三种情况会产生一个常数已用尽,所以 len
必然产生一个非常数。如果您愿意
len
要生成常量,您必须将其应用于字符串常量、数组或指向数组的指针。数组在许多方面与 slice 相似,因此这是可能的。例如,在您的示例中,只需替换:exp := []string{"HELLO"}
和:
exp := [1]string{"HELLO"}
就够了。如果您希望编译器计算初始值设定项,请使用
...
足够了:exp := [...]string{"HELLO"}
见 example on Go Playground .请注意,因为
exp
现在是一个数组,而不是一个 slice ,某些操作不能在/使用 exp
上执行.
关于go - 在golang中获取数组的长度并将其存储在const中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60244368/