In Python or really any object oriented language we have the concept of classes. So, if you imagine we’re a casino, we might have a class called ‘Deck’ – that is, deck of cards. Associated to that class, we might have functions to shuffle the cards, pick a random card etc…
Well, given that Golang isn’t an object oriented language, we don’t have the concept of classes, but we can think of custom types as being somewhat like classes in many ways.
A type in Golang takes an existing data type and extends it. For example, we’ve looked at slices before, we might define one like this: card := string which would be an empty slice of strings.
We can do the same using a type statement: type deck string here, we have defined deck as a new type, which is a slice of strings. Why would we want to do that? Well, we can now extend the functionality of that type by adding methods that are tied to that type.
Confused? Let’s make this a bit clearer. Here, I have created a file called deck.go. Here I am:
- Assigning it to the main package
- Importing the format module
- Creating a new deck type
- Associating a function with that deck type
Point 4 here is the important bit. The data type we just created, called Deck, now has a print function.
We will loop back around and look at that code snippet in more detail shortly. First, let’s look at the main file.
In this file:
- We’re creating a new variable called cards which is an instance of the deck type we just created. So, cards is a slice of strings (just like deck).
- We’re appending that slice with a new value
- We’re calling the print() function we defined in the deck.go file above
Wait, so now it’s starting to make sense. We created a new data type and associated a function with it. That means, every instance of that data type can call on those functions in the short hand method of instance.function_name().
This kind of feels like a class in many other programming languages.
Right so now let’s flip back up to the deck.go script above. We are:
- Passing the instance of deck (in this case the card variable) into the function as (d deck) – it doesn’t have to be called d, you can call it whatever you like.
- We then loop through each of the cards in the slice and print them out.
So there we have it, a quick intro into class like concepts in Golang.