duanliang4009 2014-02-09 09:34
浏览 55
已采纳

var vs:=在Go中

In the Go web server example here: http://golang.org/doc/effective_go.html#web_server

The following line of code works

var addr = flag.String("addr", ":1718", "http service address")

but changing it to

addr := flag.String("addr", ":1718", "http service address")

is a compilation error. Why? Does it have anything to do with the face that the return type of the function is *string instead of string? What difference does that make?

UPDATE: Thanks for pointing out that := is not allowed at the top level. Any idea why this inconsistency is in the spec? I don't see any reason for the behaviour to be different inside a block.

  • 写回答

3条回答 默认 最新

  • dongpaipu8394 2014-02-09 13:28
    关注

    On the updated question: there is actually a difference between long and short declarations, being in that short form allows redeclaration of variables.

    From spec:

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

    field1, offset := nextField(str, 0)
    field2, offset := nextField(str, offset)  // redeclares offset
    a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere
    

    So I'd say the := operator is not pure declare, but more like declare and assign. Redeclaration in toplevel is not allowed, so neither are short declarations.

    Another reason for this might be syntax simplicity. In Go all toplevel forms start with either type, var or func. Short declarations there will ruin all the cuteness.

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

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题