Go has a speciel type struct
to define custome type with named fields. Struct act like collection of attributes/properties similar to classes in OOPS languages out there, but not exactly.
Structs
Struct can have named attributes of any type and methods can be defined to operate on that. Lets define a Person
struct that will contain first_name
, last_name
and age
So that’s it, we just defined a person struct with some attributes. Let’s use it. There are many way to initialize an struct, here are some
Note when we initialize it without providing any value, go assign default value to each attributes, depending on there types, like first_name
, last_name
will be assigned a blank string “” and age will be assigned 0.
This can also be in initialized using new
function that allocates memory and return pointer.
But most used way is to initialize while passing values to it, here is how
Methods
In Go, Methods are similar to func
except that they have a receiver to operate on. To get full_name of a person we would love to define a method to Person
struct like
Well done Jack! But problem with this method is, it is printing full_name
to standard output. But in real world we would need our full_name
to return full name of a person. Here is how
Just FYI Jack, struct can also have embedded types, not just legacy types. Here is an example of struct Employee
Now to initilize it we need to follow same way, but first argument should be of type person, like
Note that method defined on struct Person
is alo available directly and indirectly to employee.
Happy Structing :)
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM