Introduction#
I have seen many people coming from Python background struggling with Go. What I have obeserved it they write code that is limited to writing functions and calling them. They never leverage design constructs such as abstraction, encapsulation, inheritance, composition etc. I can understand their pain because I’ve been in the same boat.
In today’s post I’ll compare how we write classes in Python vs how we do the same thing in a Go way.
What is a class composed of?#
- Attributes in form of variables
- Behavior in form of methods
Example in Python#
Consider the following code in Python that defines a simple Person class with a name attribute and a greet method:
| |
If you’re a Python programmer looking to learn Go, you’ll be happy to know that Go has a similar concept to classes called “structs”. Structs are similar to classes in that they allow you to define a custom data type with its own fields and methods.
Struct to define the structure and attributes#
To define a struct in Go, you use the type keyword followed by the name of the struct and a set of curly braces containing the fields. Here’s an example of a simple struct called Person:
| |
This defines a struct called Person with two fields: name and age, both of which are of type string and int respectively.
Method or behaviour using receiver function#
You can also define methods on your structs by using the func keyword and attaching the method to the struct using the (p *Person) syntax, where p is the receiver of the method and Person is the type of the receiver. Here’s an example of a method called SayHello that prints a greeting to the console:
| |
To create an instance of a struct, you can use the new function or the shorthand syntax :=. Here’s an example of both:
| |
You can also define a “constructor” function to create instances of your struct. This can be useful if you want to perform some initialization logic when creating a new instance. Here’s an example of a constructor function for the Person struct:
| |
You can then use this constructor function to create a new instance of the Person struct like this:
| |
I hope this tutorial has helped you understand how to define and use structs in Go as a Python programmer. Structs are a powerful and flexible way to define custom data types in Go, and I encourage you to explore them further.
Thank you for reading!