在 C++ 中你可以这样写:
std::string foo()
{
const static std::vector<std::string> unchanging_data_foo_uses = {"one", "two", "three"};
...
}
我一直认为这样做的一个重要优点是这个成员只需要设置一次,然后在后续调用中不需要做任何事情,它只是坐在那里,这样函数就可以完成它的工作。在 Go 中有一个很好的方法来做到这一点吗?也许编译器足够聪明,可以查看变量的值是否不依赖于参数,然后它可以像上面的代码一样对待它而不进行任何重新评估?
在我的具体情况下,我正在编写一个 Go 函数来将数字转换为单词(例如 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 { ... }
关于c++ - 什么是 C++ static const 函数变量的 Go 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25458551/