C++静态常量函数变量的 Go 等价物是什么?

What's the Go equivalent of a C++ static const function variable?

本文关键字:Go 等价物 是什么 变量 静态 常量 函数 C++      更新时间:2023-10-16

在c++中你可以这样写:

std::string foo()
{
    const static std::vector<std::string> unchanging_data_foo_uses = {"one", "two", "three"};
    ...
}

我一直认为这样做的一个重要优点是,这个成员只需要设置一次,然后在随后的调用中不需要做任何事情,它只是坐在那里,以便函数可以做它的工作。在Go中有什么好的方法可以做到这一点吗?也许编译器足够聪明,可以看到变量的值是否不依赖于参数,那么它可以像上面的代码一样对待它,而不做任何重新评估?

在我的具体情况下,我正在编写一个Go函数来将数字转换为单词(例如42 ->"42")。下面的代码可以工作,但是我觉得在每次调用时设置字符串数组的工作很繁琐,特别是因为它是递归的:

func numAsWords(n int) string {
    units := [20]string{
        "zero",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen",
    }
    tens := [10]string{
        // Dummies here just to make the indexes match better
        "",
        "",
        // Actual values
        "twenty",
        "thirty",
        "forty",
        "fifty",
        "sixty",
        "seventy",                                                                                                                                
        "eighty",
        "ninety",
    }
    if n < 20 {
        return units[n]
    }
    if n < 100 {
        if n % 10 == 0 {
            return tens[n / 10]
        }
        return tens[n / 10] + "-" + units[n % 10]
    }
    if n < 1000 {
        if n % 100 == 0 {
            return units[n / 100] + " hundred"
        }
        return units[n / 100] + " hundred and " + numAsWords(n % 100)
    }
    return "one thousand"
}

你可以使用全局变量,这在go中是完全可以接受的,特别是在特定的情况下。

虽然不能在数组中使用关键字const,但可以使用如下命令:

//notice that since they start with lower case letters, they won't be
// available outside this package
var ( 
    units = [...]string{...}
    tens = [...]string{ ... }
)
func numAsWords(n int) string { ... }
游乐场

Go语言中不存在静态变量的概念。
但是,您仍然可以通过将它们标记为常量来实现您想要的目标。

Go中的常量就是常量。它们在编译时创建时间,即使在函数
中定义为局部变量

https://golang.org/doc/effective_go.html常量

可以在创建函数时保留的闭包中定义这些变量。(您定义并立即调用一个匿名函数来创建这些数组,然后创建并返回您的函数。然后将匿名函数的返回值(您的函数)赋给一个全局变量。

这个解决方案完全是一个hack——因为它是可怕的不可读的(数组中有什么?),而且因为你滥用闭包来避免混乱你的全局命名空间。一个更好的主意可能是让函数成为一个类方法。

但是我的解决方案达到了您的目标:数组只定义一次,并且不会使任何命名空间混乱。