Member-only story
Object-Oriented Concepts in Go: A Comprehensive Overview
In Go language, although there are no classes like in object-oriented languages, partial object-oriented programming (OOP) concepts are supported through struct types and methods.
Encapsulation
Encapsulation involves hiding the implementation details of an object, making it invisible to other objects, thus achieving decoupling.
Consider the following struct:
type Student struct{
name string
rollNo uint64
}
The name
and rollNo
fields are private because they start with lowercase letters. To provide public access, corresponding getter and setter methods can be defined for these fields.
func (s *Student) GetName() string {
return s.name
}
func (s *Student) SetName(name string) {
s.name = name
}
func (s *Student) GetRollNo() uint64 {
return s.rollNo
}
func (s *Student) SetRollNo(roll uint64) {
s.rollNo = roll
}
Now, other parts of the program can create Student
struct objects and access name
and rollNo
through public getter and setter methods, achieving encapsulation.
Abstraction
Data abstraction is a design pattern where data is visible only to semantically related functions to prevent misuse. Successful data abstraction leads to frequent hiding of data as a design principle in both object-oriented and purely functional programming.