Answer the question
In order to leave comments, you need to log in
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
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
}
func Report(s BigStruct)
s := BigStruct{}
// заполняем поля
Report(s)
func Report(s *BigStruct)
s := BigStruct{}
// заполняем поля
Report(&s) // тут добавился & - берём адрес структуры, а не саму структуру
// создаём переменную s сразу с типом указатель на BigStruct
s := &BigStruct{}
// заполняем поля
Report(s) // поскольку s уже является указателем - & тут не нужен
var s *BigStruct
var i *int
i = new(int)
*i = 10 // пишем значение
fmt.Printf("i: %v\n", i)
fmt.Printf("*i: %v\n", *i)
i: 0xc0000160d8 (это адрес памяти, где лежит значение переменной i)
*i: 10 (а это её значение)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question