【问题标题】:Using pure functions in a constant declaration在常量声明中使用纯函数
【发布时间】:2022-01-23 08:08:24
【问题描述】:

如果我有这个纯函数:

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 str1 = PureFunction(4)
const str1 = PureFunction(5)

我得到错误:

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

理论上编译器应该能够看到这些值是常量。

有没有办法做这样的事情?比如将函数定义为纯函数或其他帮助编译器的技巧?

【问题讨论】:

    标签: go constants purely-functional


    【解决方案1】:

    函数必须被计算,所以它不是一个常数,不能这样使用。

    您可以改用var

    常量是defined as:

    有布尔常量、符文常量、整数常量, 浮点常量、复数常量和字符串常量。 符文、整数、浮点数和复数常量统称为 称为数字常量。

    使用var

    var str1 = PureFunction(0)
    var str1 = PureFunction(4)
    var str1 = PureFunction(5)
    

    【讨论】:

    • 我知道这一点。我的问题更多是关于是否有任何方法可以强制编译器在编译时而不是运行时计算值,因为它永远不会改变。
    【解决方案2】:

    常量必须能够在编译时赋值。 const 的值不能是运行时计算的结果。函数是在运行时计算的,因此不能用于声明一个常量。

    如果你甚至做了类似this 的事情,其中​​值根本不会改变,编译器仍然会给你一个错误。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 我知道这一点。我的问题更多是关于是否有任何方法可以强制编译器在编译时而不是运行时计算值,因为它永远不会改变。
    猜你喜欢
    • 2020-10-19
    • 2017-12-02
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多