What does this piece of code mean?

Refer to the link here : https://go.dev/play/p/mPYw900P1vT

Line 11-13. What does it mean to pass a “pointer” to a struct and return “address” of the struct?

My understanding is that “&” will return the address of the entity. Why are we returning the address when we want the actual entity?

So I have two questions:

  1. What does returning a pointer to MyStruct mean?
  2. Why are we returning the address to the struct when we want the actual value?

I am new to this and its confusing as I see this pattern in all codes. especially while using third party libraries like net/http.

Hi @vinayak.vg,

  1. Returning a pointer to a struct means that the struct does not get copied.

Go has two modes of passing data two and from functions:

  • By value. Here, the data is copied when it gets passed to a function or is returned from a function. If the receiver manipulates the received copy, the original data remains unaltered.
  • By reference. In this case, only a pointer to the data is passed to a function, or returned from it. If the receiver manipulates the data, it manipulates the original data.

Here is a video that visualizes the essence of pointers. (Tip: ensure to watch the video rather than only reading the text below the video. This text is only the transcript. The video adds visual explanations that go beyond what text can express.)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.