go - 在golang中获取数组的长度并将其存储在const中

标签 go

这个问题在这里已经有了答案:





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 if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated. Otherwise, invocations of len and cap are not constant and s is evaluated.



自从您调用 lenlen(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/

    相关文章:

    go - 有没有办法拦截go函数?

    go - 数组可以在 Go 中有方法吗?

    session - gorilla / session : Session be managed (persist changes) between handlers?

    去旅游#10 : What is the use of that done channel in the crawler solution

    c - 使用 Go 和 OpenCV 读取/写入图像中的 ICC 配置文件

    go - BigQuery golang 客户端 : which context to use?

    mysql - 使用 Go 和 MySQL 设置具有容错能力的服务器(故障转移)

    arrays - 如何解决函数中的 Go 数组大小

    Go:使用 strconv.ParseFloat 将字符串转换为 float 返回 0

    sockets - Go:在一个函数中接受不同的套接字调用