C++静态常量函数变量的 Go 等价物是什么?
What's the Go equivalent of a C++ static const function variable?
在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——因为它是可怕的不可读的(数组中有什么?),而且因为你滥用闭包来避免混乱你的全局命名空间。一个更好的主意可能是让函数成为一个类方法。
但是我的解决方案达到了您的目标:数组只定义一次,并且不会使任何命名空间混乱。
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- python集合的C++等价物是什么.计数器
- C++中是否存在 std::conditional 的懒惰等价物?
- 为什么'Go To Definition'给我多种选择?
- std::endl,在 Python 中是否有等价物?(返回 + 刷新)
- 为什么在 Go 中将 float64 转换为 int32 会给出负数?
- 在本征C++中 MKL 的函数"zgges"等价物是多少?
- Go 是否支持调用C++函数?
- 在C++中使用std或boost库的Qtimer等价物是什么
- GLM中的Java Matrix4.transform等价物
- Go/C++gRPC客户端通道和存根生命周期
- 是否有用于"go to variable type definition" C++中"auto"变量的 Visual Studio 键盘快捷方式?
- 对于std::bitset,是否有一个ffs()等价物
- 指定 go build 的 C++ 版本
- std::move() 或其在局部变量上的显式等价物可以允许 elision 吗?
- 这个 matlab 代码的C++等价物是什么(fread matlab vs fread C/C++)?
- 如何在SWIG的帮助下使用C++Go代码中的共享库?
- 有没有可以与 boost::uniform_int 相媲美的 Go 函数?
- 在Qt C++项目中使用Go
- C++静态常量函数变量的 Go 等价物是什么?