doubu0897 2018-02-28 03:36
浏览 195
已采纳

初始化const变量

How can I initialize KILO variable with const type?

const KILO = math.Pow10(3)

Because I have an errror

const initializer math.Pow10(3) is not a constant
  • 写回答

1条回答 默认 最新

  • douyuliu9527 2018-02-28 03:39
    关注

    Constant declarations cannot contain function calls (with some exceptions, see below), they must be evaluated at compile time while a function call is carried out at runtime.

    Quoting from Spec: Constants:

    A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants.

    And quoting from Spec: Constant expressions:

    Constant expressions may contain only constant operands and are evaluated at compile time.

    Note that there is a small set of (builtin) functions that may be called in constant declarations such as unsafe.Sizeof(), but generally you can't do that.

    So just use

    const Kilo = 1000  // Integer literal
    

    Or

    const Kilo = 1e3   // Floating-point literal
    

    For an extensive introduction to Go constants, read blog post: Constants

    If for some reason you do need to call a function, you cannot store it in a constant, it must be a variable, e.g.:

    var Kilo = math.Pow10(3)
    

    Also see related Writing powers of 10 as constants compactly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部