W
W
worldhellok2021-09-12 16:03:30
go
worldhellok, 2021-09-12 16:03:30

How to understand when to put a pointer?

Good afternoon! Tell me please, I noticed that in golang very often used * seems to be called a pointer, so how to understand when to put this asterisk * ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2021-09-12
@worldhellok

The pointer, in fact, stores the address of some data (variable, structure, slice, etc.).
In other words, it "points" to the data area.
To understand how to use it, you first need to understand what it is generally used for.
Imagine that you have a structure that contains many different fields that contain a large amount of data.
For example:

type BigStruct struct {
    field1 int
    filed2 string
    field3 uint
    field4 []byte
    ...
    field50 string
}

Suppose that after creating this structure and filling in all its fields, it occupies 300 MB in memory.
If you make a function that will take such a structure as an argument, for example like this, then every time this function is called, the entire structure (300mb) will be copied each time. Example:
func Report(s BigStruct)
s := BigStruct{}
// заполняем поля
Report(s)

To avoid such a mega load, you can transfer not a copy of the data, but a pointer, i.e. the address in memory where the structure itself is stored.
To do this, you need to declare the function argument as a pointer, i.e. put *. And the code will look like this.
func Report(s *BigStruct)
s := BigStruct{}
// заполняем поля
Report(&s) // тут добавился & - берём адрес структуры, а не саму структуру

Or the second option
// создаём переменную s сразу с типом указатель на BigStruct
s := &BigStruct{}
// заполняем поля
Report(s) // поскольку s уже является указателем - & тут не нужен

In general, * is used:
- when you need to declare a variable
var s *BigStruct
- when you need to read / write a value that is stored at the pointer address
var i *int
    i = new(int)
    *i = 10 // пишем значение

    fmt.Printf("i: %v\n", i)
    fmt.Printf("*i: %v\n", *i)

The output will be something like this
i: 0xc0000160d8 (это адрес памяти, где лежит значение переменной i)
*i: 10 (а это её значение)

& (ampersand) is used when you need to get the address of a variable.
Another use case is if you need to be able to modify the data of a function parameter. If you need examples - let me know, I'll write.

D
Developer, 2021-09-12
@samodum

As needed.
I recommend reading first the theory about what pointers, variables, types and data structures are.
Without basic concepts, you won't get far.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question