继续-何时使用“&MyStruct {1,2}”语法实例化结构并获取指向该结构的指针会有用吗?

I have been following the tour of the Go programming language to get familiar with the language, and one feature of the language left me wondering.

In the step about Struct Literals, they explain that you can instantiate a structure by multiple ways:

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
    v3 = Vertex{}      // X:0 and Y:0
    p  = &Vertex{1, 2} // has type *Vertex
)

I have no problem understanding how the three first ways are working and when they can be useful, but I cannot figure out any use-case for the last solution p = &Vertex{1, 2}.

Indeed, I cannot think of any case where one would have to instantiate a *Vertex without having already a variable of type Vertex available and used in your code:

func modifyingVertexes(myVertex *Vertex) {
    myVertex.X = 42;
}

func main() {
    myVertex := Vertex{1, 2}

    modifyingVertexes(&myVertex)

    fmt.Println(myVertex.X)
}

I could see a use if the following was possible:

func modifyingVertexes(myVertex *Vertex) {
    myVertex.X = 42;
}

func main() {
    modifyingVertexes(&Vertex{1, 2})

    fmt.Println(???.X) // Accessing the vertex initialized in the modifyingVertexes func call
}

But since I don't think it's possible, I really have no idea on how it could be used?

Thanks!

This is a very common Go idiom, returning the address of an initialized struct variable.

package main

import "fmt"

type Vertex struct {
    X, Y int
}

func NewVertex(x, y int) *Vertex {
    return &Vertex{X: x, Y: y}
}

func main() {
    v := NewVertex(1, 2)
    fmt.Println(*v)
}

Playground: https://play.golang.org/p/UGOk7TbjC2a

Output:

{1 2}

It's also a very common idiom for hiding unexported (private) struct fields.

package main

import "fmt"

type Vertex struct {
    x, y int
}

func NewVertex(x, y int) *Vertex {
    return &Vertex{x: x, y: y}
}

func (v *Vertex) Clone() *Vertex {
    return &Vertex{x: v.x, y: v.y}
}

func main() {
    v := NewVertex(1, 2)
    fmt.Println(*v)

    w := v.Clone()
    fmt.Println(*w)
}

Playground: https://play.golang.org/p/ScIqOIaYGPn

Output:

{1 2}
{1 2}

In Go, all arguments are passed by value. Using a pointer for large structs is more efficient. A pointer is also necessary if you wish to change the value of a struct argument.

Another way to think about the two styles of initialization (e.g., foo{} and &foo{}) is through what you hope to accomplish. If you need a value object which will never change, then foo{} does just fine. On the other hand, if you will need to later change an object, then a reference is best. For example:

// using a value object because it will never change
oneHundredDollars := Cash{Amount: 100, Currency: "Dollars"}

// using a reference because the account's balance will change.
a := &Account{Balance: 0}

// changes Balance
a.Deposit(oneHundredDollars)