我使用 go playground 来尝试这段代码:
package main
func main() {
exp := []string{"HELLO"}
const length = len(exp)
}
Run Code Online (Sandbox Code Playgroud)
但它向我抛出了这个错误:
./prog.go:6:8: const 初始值设定项 len(exp) 不是常量
我可以看到这是因为 exp 的长度是可变的。如何获取当前长度并将其存储在整数常量中?
我认为我需要反射模块来做到这一点,但我不知道该怎么做。我尝试使用reflect.ValueOf但它没有用。
exp := []string{"HELLO"}
const length = len(reflect.ValueOf(exp).Interface().([]string))
Run Code Online (Sandbox Code Playgroud) go ×1