Encapsulation in Go: Structs and Controlled Access
Understanding Encapsulation in Go
Go, although not a traditional Object-Oriented Programming (OOP) language, provides encapsulation through the use of structs and package-level visibility. Encapsulation in Go is about controlling access to data and methods within packages, enabling you to create robust and maintainable applications.
To illustrate, consider a Go struct representing a bank account. Without encapsulation, the account balance could be directly altered. With encapsulation, however, the balance can only change through specific methods, like depositing or withdrawing.
Encapsulation: Managing Data Privacy with Visibility
In Go, data privacy is managed through the visibility of identifiers. By convention, identifiers starting with a lowercase letter are unexported and accessible only within the same package. In contrast, identifiers that begin with an uppercase letter are exported and accessible from other packages.
For example, let's consider a Go struct named Person, which includes an unexported field name.
person/person.go
main.go
Exported Methods for Controlled Access
In Go, encapsulation utilizes exported methods on structs to access or modify the unexported fields. Let's illustrate this through a simple example.
dog/dog.go
main.go
