Hello Gophers! Today we are going to familiarize ourselves with this great world of custom types and methods in Go. Sounds a bit overwhelming? Don't worry, by the end of this article you are going to be able to do it with eyes closed and one hand tied behind your back. So go ahead, pick up your favorite beverage, take a seat and lets dive in.
Go's Type Magic
Suppose at some point, one day, one wanted to conjure a deck of cards; he would do so in Go by first introducing what is called a custom type. Instead of saying "I want a list of strings", which is kind of a bore, he gets to name it something cool, like deck! Naming makes it easier to use and keeps the code nice and neat, just like a perfectly stacked deck of cards.
Here's the abracadabra that does the trick:
package main
type deck []string
Boom! You now have a new type called deck
, and all it really is, under the hood, is a slice of strings ([]string
). You’ve just made Go a little more readable and fun!
Making deck
Do Tricks - Adding Methods
But a deck of cards by itself is kind of boring, right? What’s a magician without a few card tricks? That's where methods come into play! In Go, you can attach methods to your custom types, making them do all sorts of cool things.
Let’s start by adding a print()
method to our deck
type so it can list out all the cards in the deck. Here's how you do it:
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
Hold up—what just happened? Let me break it down for you:
-
func (d deck) print()
: This is a method calledprint()
that belongs to ourdeck
type. The(d deck)
part is called a receiver. You can think of it like saying, “Heydeck
, here’s what I want you to do when I callprint()
on you.” - Inside
print()
, we’re looping through each card in the deck and printing out its index (i
) and its value (card
). Simple, yet powerful!
Here's the full picture:
package main
import "fmt"
type deck []string
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func main() {
cards := deck{"Ace of Spades", "Two of Hearts", "Three of Diamonds"}
cards.print()
}
Run this, and you’ll get something like:
0 Ace of Spades
1 Two of Hearts
2 Three of Diamonds
Look at that! Your deck knows how to introduce itself. You've made a talking deck—how cool is that?
Not Just Cards: Real-Life Use Cases
So you’ve learned to make a deck of cards, but what else can you do with custom types and methods in Go? Glad you asked—because the possibilities are endless. Let’s walk through a few fun examples that go beyond just cards.
1. Managing Students Like a Boss
Imagine you’re a teacher with a list of students. Instead of using a boring old slice, why not create a new type called students
?
type students []string
func (s students) print() {
for i, student := range s {
fmt.Println(i, student)
}
}
func main() {
class := students{"Alice", "Bob", "Charlie"}
class.print()
}
Now, when you need to list all the students, you just call class.print()
. It’s like having your own roll call assistant!
2. Shopping Cart for an E-Commerce App
Running an online store? You’ll probably want a cart
type to manage the items customers add to their shopping cart.
type cart []string
func (c cart) printItems() {
for i, item := range c {
fmt.Printf("%d: %s\n", i, item)
}
}
func main() {
shoppingCart := cart{"Laptop", "Mouse", "Keyboard"}
shoppingCart.printItems()
}
This is super handy for quickly listing everything in the cart without any extra effort. You could even add methods like addItem()
or removeItem()
to make it more powerful.
3. Bank Account Transactions
How about keeping track of bank transactions? You could create a transactions
type and add methods for printing and calculating balances.
type transactions []float64
func (t transactions) printHistory() {
for i, transaction := range t {
fmt.Printf("Transaction %d: $%.2f\n", i, transaction)
}
}
func main() {
account := transactions{100.0, -50.0, 25.5}
account.printHistory()
}
This way, you can quickly see every deposit and withdrawal and easily manage your bank history—without even needing an app!
Why Custom Types Are Awesome
Custom types and methods are all about making your life easier. By grouping related data and functionality together, you make your code more readable, reusable, and much more manageable. Instead of juggling random slices and utility functions all over the place, you have something that makes sense to your project.
A deck
knows how to print itself. A cart
knows what’s inside it. A students
type knows how to call roll. It’s all about attaching meaning to your data and giving it superpowers to do useful things.
Your Next Magic Trick?
Why not give it a shot yourself? Try creating a new type for something you work with—maybe a list of favorite movies or tasks for your to-do app—and add a method or two that makes it useful.
And there you have it—you’ve learned how to create custom types and add methods to them in Go, making your code more expressive and powerful. Now, it’s your turn to be the magician! Who knows, maybe your next trick will be the best one yet.
Happy Go coding, my friend!
Top comments (0)