doubu0897 2018-02-28 11:36
浏览 192
已采纳

初始化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 11: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.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题