var vs:=在Go中 [英] var vs := in Go

查看:61
本文介绍了var vs:=在Go中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下Go Web服务器示例中: http://golang.org/doc/effective_go. html#web_server

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

以下代码行有效

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

但将其更改为

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

是编译错误.为什么?它与函数的返回类型为*string而不是string有关吗?这有什么区别?

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.

推荐答案

在更新的问题上:长声明和短声明之间实际上是有区别的,采用这种短格式可以重新声明变量.

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

来自规范:

与常规变量声明不同,简短的变量声明可以重新声明变量,前提是它们最初是在相同类型的同一块中较早地声明的,并且至少一个非空白变量是新变量.因此,重新声明只能出现在多变量简短声明中.重新声明不会引入新变量;只是为原始值分配了一个新值.

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

所以我想说:=运算符不是纯粹的 declare ,而是更像 declare and Assign . 不允许在顶层进行重新声明,因此简短声明也不可以.

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.

另一个原因可能是语法简单.在Go中,所有顶级表单都以typevarfunc开头.在那里简短声明会毁掉所有可爱之处.

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.

这篇关于var vs:=在Go中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆