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.
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
