Member-only story
Object-Oriented Programming (OOP) in Go: A Pragmatic Approach
Go, often praised for its simplicity and efficiency, might not immediately looks like as an object-oriented language. However, Go offers a unique and pragmatic approach to OOP that aligns well with its core philosophies. Let’s get into how Go enables encapsulation, inheritance, and polymorphism — the cornerstones of OOP.
Embracing Encapsulation with Structs and Methods
In Go, the fundamental building block of OOP is the struct
. A struct
is a composite data type that groups together related fields (variables) under a single name. This is equal to the concept of an object encapsulating data and behavior.
type Car struct {
Make string
Model string
Year int
}
func (c Car) Start() {
fmt.Println("The car starts with a roar!")
}
In this example, Car
is a struct
representing a car object. It has Make
, Model
, and Year
fields to hold the car's data. The Start()
method is associated with the Car
struct, representing an action the car can perform.
Inheritance Through Composition: The “is-a” Relationship
Go doesn’t have traditional class-based inheritance. Instead, it promotes composition, also known as the “has-a” relationship. This means…