Answer the question
In order to leave comments, you need to log in
What are pointers used for in Go, and where is the best place to use them?
There is a code. ( Go Playground )
package main
import "fmt"
type person struct {
Name string
Age int
}
func showMePerson(d person) {
fmt.Printf("Person name: %s\nPerson age: %d\n", d.Name, d.Age)
}
func showMePerson2(d *person) {
fmt.Printf("Person name: %s\nPerson age: %d\n", d.Name, d.Age)
}
func main() {
d := person{"Nick", 10}
showMePerson(d)
fmt.Println("======================")
showMePerson2(&d)
}
Answer the question
In order to leave comments, you need to log in
When you pass a structure to the showMePerson function, the structure is copied and inside the function you work with its copy. At the same time, it most likely jumps through the stack and does not load the garbage collector.
When passing a structure by pointer to the showMePerson2 function, you work with the same structure that you passed and can change it, for example. But it leaks into your heap, creating a load on the collector.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question