在Go中,”var”是用于声明变量的关键字。

huangapple go评论105阅读模式
英文:

var vs := in Go

问题

在这个Go Web服务器的例子中: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有关吗?这有什么区别?

更新:感谢指出在顶层不允许使用:=。有没有想过为什么规范中存在这种不一致性?我没有看到在块内部行为不同的任何理由。

英文:

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.

答案1

得分: 42

在Go语言中,顶层变量的赋值必须以var关键字为前缀。只有在块内部才允许省略var关键字。

package main

var toplevel = "Hello world"         // 需要var关键字

func F() {
        withinBlock := "Hello world" // 不需要var关键字
}
英文:

In Go, top-level variable assignments must be prefixed with the var keyword. Omitting the var keyword is only allowed within blocks.

package main

var toplevel = "Hello world"         // var keyword is required

func F() {
        withinBlock := "Hello world" // var keyword is not required
}

答案2

得分: 32

在更新的问题中,长声明和短声明实际上是有区别的,短声明允许重新声明变量。

根据规范,与常规变量声明不同,短变量声明可以重新声明变量,前提是它们在同一代码块中以相同的类型进行了原始声明,并且至少有一个非空白变量是新的。因此,重新声明只能出现在多变量的短声明中。重新声明不会引入新变量;它只是给原始变量赋予新值。

所以我可以说 := 运算符不仅仅是纯粹的“声明”,更像是“声明和赋值”。
在顶层重新声明是不允许的,因此短声明也不被允许。

这可能是为了语法的简洁性。在Go语言中,所有的顶层形式都以 typevarfunc 开头。在那里使用短声明会破坏所有的可爱之处。

英文:

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.

答案3

得分: 11

《Go编程语言规范》

短变量声明

短变量声明使用以下语法:

ShortVarDecl = IdentifierList ":=" ExpressionList .

短变量声明只能出现在函数内部。

在你的例子中,将变量声明语句从函数体外部改为短变量声明语句:

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

会导致编译器错误:"非声明语句出现在函数体外部"。

英文:

> The Go Programming Language Specification
>
> Short variable declarations
>
> A short variable declaration uses the syntax:
>
> ShortVarDecl = IdentifierList ":=" ExpressionList .
>
> Short variable declarations may appear only inside functions.

In your example, changing the variable declaration statement outside a function body

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

to a short variable declaration statement outside a function body

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

fails with compiler error "non-declaration statement outside function body."

huangapple
  • 本文由 发表于 2014年2月9日 17:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/21657446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定