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!