H
H
hitakiri2017-08-08 16:58:45
go
hitakiri, 2017-08-08 16:58:45

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)
}

I can't figure out what properties the showMePerson and showMePerson2 functions differ in . And in what cases, which one is better to use.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-08-08
@hitakiri

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 question

Ask a Question

731 491 924 answers to any question