dtkmejg127475 2019-05-04 17:07
浏览 74
已采纳

组合无类型和类型常量时的类型推断

When declaring two const variables (one typed and one untyped), and printing out the type of the second one, like:

const x float32 = 10000
const y = 1e8 / x

fmt.Printf("the type of y: %T 
", y)
// or with reflect:
fmt.Println(reflect.TypeOf(y))

it tells me, that y is of type float32.

Well this doesn't come as a surprise, since the the untyped const variable y is defined as dividing an untyped float constant by a typed float constant and therefore the type might be inferred.
According to "Go by Example" (https://gobyexample.com/constants), constants never have a type, unless explicitly provided. However, according to the official Go blog documentation, untyped constants do have hidden types that get inferred, but let the constant remain untyped until a type is needed.

I would have assumed, that y would still be an untyped float constant. However, when using it for assigning a new variable, Goland's inspector tells me, that the type can be omitted:

const z float32 = y 
//        ^^^ type can be ommitted

So finally, my question would be:
Is it impossible to declare an untyped constant out of typed constant expressions?

  • 写回答

1条回答 默认 最新

  • dsqnonh2763 2019-05-04 17:16
    关注

    It's not clear to me what the actual problem here is. The IDE suggestion seems to say that the type of z can be inferred from the type of y, so you can omit the explicit declaration. That seems correct.

    The declaration of y is still untyped though, so what seems to be wrong? The inferred type of constants is affected from its constituents - they can't be ignored, otherwise you get a type mismatch. You may be interested to read how type inference is typically implemented; this isn't necessarily the case for Go, but it should be a decent introduction in general to help you understand the underlying mechanism here.


    Note that you could omit the type of x too, and the end result type would be float64, so all of it can be inferred without types.

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿