Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common to have struct members be pointers?

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?

like image 854
AndrewH Avatar asked Oct 27 '15 06:10

AndrewH


People also ask

Do structs have to be pointers?

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.

Can a pointer be a member of a structure?

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.

Why do we use pointers for structs?

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.

How structure members can access by using pointers?

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.


1 Answers

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.

like image 181
captncraig Avatar answered Nov 16 '22 03:11

captncraig