var vs:=在Go中

编程入门 行业动态 更新时间:2024-10-18 20:27:20
本文介绍了var vs:=在Go中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

In the Go web server example here: golang/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中,所有顶级表单都以type,var或func开头.在那里简短声明会毁掉所有可爱之处.

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中

本文发布于:2023-11-11 23:08:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:var

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!