Structs and Methods in Golang (When Your Code Hits the Gym!)

Go doesn’t have classes, but don’t worry—structs and methods have got your back!  Think of structs as the muscles and methods as the workouts that make them stronger. Let’s pump up your Go skills! 

What is a Struct? (Go’s Version of a Lightweight Class)

A struct in Go is a way to group related data together, like a class but without unnecessary fluff.

package main
import "fmt"

type Car struct {
    Brand string
    Year  int
}

func main() {
    myCar := Car{Brand: "Tesla", Year: 2023}
    fmt.Println("I drive a", myCar.Brand, "from", myCar.Year)
}

Here, Car is our custom data type, grouping Brand and Year. Boom! You just created an object. 

Adding Methods (Giving Structs Superpowers)

In Go, methods are just functions with a receiver—meaning they belong to a struct. This is how we make structs do things.

package main
import "fmt"

type Car struct {
    Brand string
    Year  int
}

func (c Car) Drive() {
    fmt.Println("The", c.Brand, "goes vroom!")
}

func main() {
    myCar := Car{Brand: "Lamborghini", Year: 2022}
    myCar.Drive() // Calls the Drive method
}

Now, Car objects can drive!

Pointer Receivers (Modifying Structs Inside Methods)

Want to modify a struct inside a method? Use a pointer receiver (*StructName).

package main
import "fmt"

type Car struct {
    Brand string
    Year  int
}

func (c *Car) Upgrade() {
    c.Year++ // Increments the year
}

func main() {
    myCar := Car{Brand: "Toyota", Year: 2020}
    fmt.Println("Before upgrade:", myCar.Year)
    myCar.Upgrade()
    fmt.Println("After upgrade:", myCar.Year)
}

The Upgrade method actually modifies the original Car object. Without pointers, it would only modify a copy! 

Structs + Methods = Go’s Version of OOP 

Go’s combination of structs and methods allows you to:

  • Group data together (structs).
  • Add functionality (methods).
  • Modify data safely (pointer receivers).

No inheritance drama, no bloated classes—just clean, simple, efficient code. 

Structs and methods in Go let you organize and enhance your code without the mess of traditional OOP. Now go flex those Go muscles! 

Post a Comment

0 Comments