Example of using struct in go for beginners

Hi, this is day 9 out of 100 days of code in go.

Today I am playing with struct type. Struct is a go way to define custom types. Use it when standard types doesn’t suite you. Enough words, lets see code examples.

Classic example Employee type

ID and Name fields is quite obvious. Manager field is the same type as struct itself, so it must be a reference type and in our business logic will point to Manager data.

Lets create first employee

Struct fields are accessible using dot notation.

Lets define a manager now and improve print function, so it will print Manger if such exist

New employee manager is created the same way as first worker variable. When using a reference to new manager variable we assign a manager to worker.

PrintEmployee function has some changes too. First it has new check if Manager reference is not nil and if so using recursion it prints Manager data.

Lets add another Employee, so we will have 3 level management organization

Note that new cto variable is using struct literals to define fields values in variable initialization step.

Output of above will be 3 level organization structure:

That’s what you need to know about struct type to use it efficiently in you go programs.

Happy coding!

Source code at Github.