0
0
Goprogramming~3 mins

Why Defining methods in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your objects could do things themselves, just like real-world items?

The Scenario

Imagine you have a simple object like a Car and you want to perform actions like starting the engine or honking the horn. Without methods, you would have to write separate functions for each action and always pass the Car as a parameter.

The Problem

This approach is slow and confusing because you must remember to pass the right object every time. It's easy to make mistakes, like passing the wrong object or forgetting to pass it at all. Your code becomes messy and hard to read.

The Solution

Defining methods lets you attach actions directly to your objects. This means you can call car.Start() instead of Start(car). It keeps your code clean, organized, and easier to understand, just like how you naturally think about objects and their actions.

Before vs After
Before
func Start(c Car) {
    // start engine
}
Start(myCar)
After
func (c *Car) Start() {
    // start engine
}
myCar.Start()
What It Enables

It enables writing clear, organized code where objects know how to do things themselves, making programs easier to build and maintain.

Real Life Example

Think of a smartphone that can make calls, send messages, and take photos. Defining methods is like giving the phone its own buttons to perform these actions directly.

Key Takeaways

Methods attach actions directly to objects.

This makes code cleaner and less error-prone.

It helps model real-world things naturally in code.