doulu4316 2014-11-26 16:28
浏览 45
已采纳

函数外部的变量声明快捷方式

This question already has an answer here:

Coming from a background in Java and C# I am very pleased with the brevity of Golang's ability to use the shortcut method for variable declaration for private variables within functions, which allows me to write:

x := 1.5

It reminds me of duck typing in a dynamic language such as Python. However, in declaring global variables outside of the scope of a function you still need to use the more verbose syntax of:

var x float64 = 1.5

I'm just wondering why the shortcut method works for private variables and not globals? I know that the designers of the language are quite experienced so I'm assuming that this isn't reflective of a feature overlooked. Is there a technical reason why this kind of type inference (and I realize that the := shortcut is not the same as proper type inference) wouldn't work at the global scope? It just seems somewhat inconsistent in terms of the design, and as an inexperienced Gopher I must admit to being thrown off by this on a couple of occasions. On the whole however I'm really enjoying Go.

</div>
  • 写回答

2条回答 默认 最新

  • dongyongyin5339 2014-11-26 17:10
    关注

    See the Ian's answer in this thread: https://groups.google.com/forum/#!msg/golang-nuts/qTZemuGDV6o/IyCwXPJsUFIJ

    At the top level, every declaration begins with a keyword. This simplifies parsing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面