在Go中使用指向字符串的指针而不是字符串的好处是什么[重复]

在Go中使用指向字符串的指针而不是字符串的好处是什么[重复]

问题描述:

This question already has an answer here:

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?

</div>

此问题已经存在 在这里有答案 p>

  • 星号在“开始”中做什么 6个答案 span> li> ul> div>

    查看一些go代码,我发现: p>

     人员结构{
    名称* string`json:“ name”`
    } 
      code>  pre> 
     
     

    ,然后是我看到的位置: p>

     动物结构{
    名称字符串`json:“ name”`
    } 
      code>  pre> 
     
     

    有什么好处 指针在这里? p> div>

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.

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

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

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.