Take, for example, the go github package. Just about every member of every struct defined is a pointer to a value rather than a value.
Is this idiomatic Go? Why?
I understand that it reduces the size of the struct (assuming the size of the pointer is less than the size of the value it points to) which may important if you are passing around structs by value a lot. But why not have a struct of values and pass the struct by pointer instead?
You can declare an int or a struct, an array of int or a struct, or a pointer to an int or a struct. The main difference between an int and a struct is that the int is a built in type where as a struct is created and described by the programmer as a new type.
A pointer could be a member of structure, but you should be careful before creating the pointer as a member of structure in C. Generally we take a pointer as a member when we don't know the length of the data which need to store.
Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.
To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.
In the github package the reason is that most structs are intended to be serialized/deserialized from json from the github api.
The reason they use *int
instead of int
is because the zero value of a pointer is nil
, while the zero value of int
is 0
. It allows the client to distingish between "this field was not included in the response" and "the value of this field is zero".
This is particularly useful for things like times, where if you do not have nilable types, you will end up with a lot of 00-00-0000 type dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With