在Go语言中,初始化一个空字符串的惯用方式是使用空引号””。

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

Idiomatic way to initialise an empty string in Go

问题

在Go语言中,你可以通过以下方式在函数中初始化一个空字符串:

var a string
var b = ""
c := ""

据我所知,这三种语句在语义上是相同的。它们中是否有一种比其他方式更符合惯用法?

英文:

In Go you can initialise an empty string (in a function) in the following ways:

var a string
var b = ""
c := ""

As far as I know, each statement is semantically identical. Is one of them more idiomatic than the others?

答案1

得分: 10

你应该选择使代码更清晰的方式。如果零值实际上会被使用(例如,当你从一个空字符串开始并将其他字符串连接到它时),最清晰的方式可能是使用:=形式。如果你只是声明变量,并且稍后将给它赋予不同的值,请使用var

英文:

You should choose whichever makes the code clearer. If the zero value will actually be used (e.g. when you start with an empty string and concatenate others to it), it's probably clearest to use the := form. If you are just declaring the variable, and will be assigning it a different value later, use var.

答案2

得分: 2

以下是要翻译的内容:

var a string
对于不太熟悉Go语言的人来说它不会立即显示为空字符串有些人可能会期望它是一些null/nil值

var b = ""
这是最明确的方式每个人都能看到它是一个包含空字符串的变量

b := ""
在我的观点中:=赋值在Go语言中非常常见这是最可读的方式当然除非它在函数体外部
英文:
var a string

It's not immediately visible that it's the empty string for someone not really fluent in go. Some might expect it's some null/nil value.

var b = ""

Would be the most explicit, means everyone sees that it's a variable containing the empty string.

b := ""

The := assigment is so common in go that it would be the most readable in my opinion. Unless it's outside of a function body of course.

答案3

得分: 1

声明空变量没有一个“正确”的方法,但有一些需要注意的事项,比如在函数体外部不能使用:=快捷方式,而可以使用var

var (
    name string
    age  int64
)

我认为var name = ""是最清晰的表示你正在声明一个空变量的方式,但我喜欢var name string类型明确性。无论如何,要考虑在哪里声明变量。有时,在函数体外部一次性声明所有变量是合适的,但通常最好在实际使用的地方附近声明变量。

Rob(Pike?)在一封邮件线程中写道关于顶层声明:

在顶层,var(或const或type或func)是必需的:每个项必须由关键字引入,以识别语句边界的ur-语法原因。随着关于分号的后续更改,我相信在某些情况下可以消除对var的需求,但由于const、type和func必须保留,这不是一个令人信服的论点。

在“短变量”声明(使用:=)中存在一定的歧义,即变量是声明还是重新声明,如规范中所述:

与常规变量声明不同,短变量声明可以重新声明变量,前提是它们最初在同一块中(或者块是函数体时在参数列表中)以相同的类型进行了声明,并且至少有一个非空白变量是新的。因此,重新声明只能出现在多变量的短声明中。重新声明不会引入新变量;它只是给原始变量赋予新值。

英文:

There isn't a right way to declare empty variables, but there are some things to keep in mind, like you can't use the := shortcut outside of a function body, as they can with var:

var (
    name string
    age  int64
)

I find var name = "" to be the clearest indication that you're declaring an empty variable, but I like the type explicitness of var name string. In any case, do consider where you are declaring variables. Sometimes all at once outside the function body is appropriate, but often nearest to where you actually use it is best.

rob (Pike?) wrote on a mailthread about top-level declaration

> At the top level, var (or const or type or func) is necessary: each item must be introduced by a keyword for ur-syntactic reasons related to recognizing statement boundaries. With the later changes involving semicolons, it became possible, I believe, to eliminate the need for var in some cases, but since const, type, and func must remain, it's not a compelling argument.

There is a certain ambiguity in "short-variable" declarations (using :=), as to whether the variable is declared or redeclared as outlined in the specs:

> Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) 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.

答案4

得分: 0

在生成的代码中(使用当前编译器 - Go 1.7.4),绝对没有任何区别,而且gometalinter对这些也没有任何抱怨。使用任何你喜欢的方式。

一些区别:

  • 你只能在函数中使用短变量声明。

  • 使用短变量声明,你可以在一行中创建多种类型的变量,例如:

      a, b := "", 0
    

以下三个应用程序生成相同的代码:

a.go

package main
import "fmt"
func main() { var a string; fmt.Println(a) }

b.go

package main
import "fmt"
func main() { var a = ""; fmt.Println(a) }

c.go

package main
import "fmt"
func main() { a := ""; fmt.Println(a) }

要验证,请构建每个应用程序(例如使用go build -o a),并在Linux上使用diff比较可执行二进制文件:

diff a b && diff a c
英文:

There is absolutely no difference in the generated code (with the current compiler – Go 1.7.4), and also gometalinter does not complain for any of those. Use whichever you like.

Some differences:

  • You can only use the short variable declaration in functions.

  • With short variable declaration, you can create variables of multiple types in one line, e.g.

      a, b := "", 0
    

The following 3 apps generate identical code:

a.go

package main
import "fmt"
func main() { var a string; fmt.Println(a) }

b.go

package main
import "fmt"
func main() { var a = ""; fmt.Println(a) }

c.go

package main
import "fmt"
func main() { a := ""; fmt.Println(a) }

To verify, build each (e.g. with go build -o a), and use diff on Linux to compare the executable binaries:

diff a b && diff a c

答案5

得分: 0

我尽量坚持使用简短的声明,原因如下:

  1. 更短
  2. 一致性
  3. 为映射、切片和结构体类型的指针分配内存。

尽管 var a stringa := "" 是相同的,但 b := []T{}var b []T 不相同。在处理切片和映射时,较短的声明不会是 nil。通常情况下(特别是对于映射),我希望分配内存。

只有在少数情况下才需要使用 var,例如,当你调用一个函数来填充某个类型的属性时。

var err error
foo.Name, err = getFooName()

在上述情况中使用 := 语法会出错,因为 foo.Name 已经声明过了。

英文:

I try to stick to the short declaration for a couple of reasons.

  1. It's shorter
  2. Consistency
  3. Allocates memory for maps, slices and pointers to structs and types.

Although var a string and a := "" are the same, b := []T{} and var b []T are not the same. When dealing with slices and maps the shorter declaration will not be nil. More often then not (especially with maps) I want allocated memory.

There are few situations where var will be needed, for instance, you are calling a function that will populate a property of a type.

var err error
foo.Name, err = getFooName()

Using := syntax in the above situation will error out since foo.Name is already declared.

答案6

得分: 0

只是在 stackoverflow 上与 Go 中的空字符串相关的内容。所以应该在这里。

英文:

just

*new(string)

It's only stuff in stackoverf related to empty strings in go. So it should be here

huangapple
  • 本文由 发表于 2017年1月18日 00:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/41702035.html
匿名

发表评论

匿名网友

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

确定