英文:
Using pure functions in a constant declaration
问题
如果我有这个纯函数:
func PureFunction(x int) string {
switch x {
case 0:
return "String zero"
case 4:
return "String four"
default:
return "Default string"
}
}
并且想要在常量声明中使用它,像这样:
const str1 = PureFunction(0)
const str2 = PureFunction(4)
const str3 = PureFunction(5)
我会得到以下错误:
PureFunction(0) (类型为 string 的值) 不是常量
PureFunction(4) (类型为 string 的值) 不是常量
PureFunction(5) (类型为 string 的值) 不是常量
理论上,编译器应该能够看到这些值是常量。
有没有办法做到这样?比如将函数定义为纯函数或者其他一些技巧来帮助编译器?
英文:
If I have this pure function:
func PureFunction(x int) string {
switch x {
case 0:
return "String zero"
case 4:
return "String four"
default:
return "Default string"
}
}
and want to use it in a constant declaration like this:
const str1 = PureFunction(0)
const str1 = PureFunction(4)
const str1 = PureFunction(5)
I get the errors:
PureFunction(0) (value of type string) is not constant
PureFunction(4) (value of type string) is not constant
PureFunction(5) (value of type string) is not constant
In theory the compiler should be able to see that these values are constant.
Is there a way to do something like this? Like defining the function as pure or some other trick to help the compiler?
答案1
得分: 3
函数需要进行评估,因此它不是一个常量,不能作为常量使用。
你可以使用var
来代替。
常量被定义为:
有布尔常量、符文常量、整数常量、浮点数常量、复数常量和字符串常量。符文、整数、浮点数和复数常量统称为数值常量。
使用var
:
var str1 = PureFunction(0)
var str1 = PureFunction(4)
var str1 = PureFunction(5)
英文:
The function has to be evaluated, so it's not a constant and can't be used as such.
What you can use instead is a var
.
Constants are defined as:
> There are boolean constants, rune constants, integer constants,
> floating-point constants, complex constants, and string constants.
> Rune, integer, floating-point, and complex constants are collectively
> called numeric constants.
Using var
:
var str1 = PureFunction(0)
var str1 = PureFunction(4)
var str1 = PureFunction(5)
答案2
得分: 2
常量必须能够在编译时赋值。常量的值不能是运行时计算的结果。函数在运行时评估,因此不能用于声明常量。
即使你像这样做了一些永远不会改变值的事情,编译器仍然会给出错误。
英文:
Constants must be able to be assigned at compile time. The value of a const can not be the result of a runtime calculation. Functions are evaluated in runtime, so can not be used to declare a const.
If you even did something like this where value won't change at all, compiler would still give you an error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论