使用指向字符串的指针而不是字符串本身在Go语言中的优势是什么?

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

What is the advantage of using a pointer to a string instead of a string in Go

问题

这里使用指针的好处是什么?

英文:

Reviewing some go code I came across this:

Person struct {
	Name *string `json:"name"`
}

and then some where I saw:

Animal struct {
    Name string `json:"name"`
} 

What is the advantage of the pointer here?

答案1

得分: 2

*声明了一个指针类型。在解码JSON时,有时会使用指向字符串的指针来区分以下JSON:

JSON        Name字段的值
{ }         nil
{name: ""}  指向""的指针

如果没有指针,无法区分解码结果中缺失值和空白值。

如果应用程序不需要进行这种区分,那么可以使用问题中显示的第二种形式。这更方便。

英文:

The * declares a pointer type. A pointer to a string is sometimes used when decoding JSON to distinguish the following JSON:

JSON        value of the Name field
{ }         nil
{name: ""}  pointer to ""

Without the pointer, it's not possible to distinguish a missing value from a blank value in the decoded result.

If the application does not need to make this distinction, then use the second form shown in the question. It's more convenient.

答案2

得分: 1

"*" 表示指针。
在你的情况下,Name 是一个指向字符串的指针类型的字段。

请参阅 http://www.golang-book.com/books/intro/8

英文:

* means pointer.
In your case, Name is a field of type pointer to string.

See http://www.golang-book.com/books/intro/8

答案3

得分: 1

* 是一个指针。

指针类型表示指向给定类型变量的所有指针的集合,称为指针的基本类型。未初始化指针的值为 nil。

这段内容来自于 Go 语言规范。我建议你阅读全部内容。

英文:

The * is a pointer.

> A pointer type denotes the set of all pointers to variables of a given
> type, called the base type of the pointer. The value of an
> uninitialized pointer is nil.

This is coming from the Go Spec. I would suggest reading it all.

huangapple
  • 本文由 发表于 2017年5月17日 00:12:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44006551.html
匿名

发表评论

匿名网友

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

确定