Hello! In this lesson, we're diving into Encapsulation and access control in Go. Unlike some languages, Go manages encapsulation through capitalization conventions. Imagine encapsulation as an invisible barrier that protects the internals of your code. In Go, identifiers (like struct fields and methods) are kept safe using naming conventions: uppercase indicates exported (public), while lowercase indicates unexported (private). This is crucial for creating robust and secure applications!
In Go, encapsulation is achieved through structs and methods. Structs bundle together data, while methods attach functionality. Please note that in Go, the distinction between exported (public) and unexported (private) identifiers in Go is meaningful only across package boundaries, so all code snippets we'll discuss today will span multiple files. As example, imagine to be coding a multiplayer game; you could create a Player
struct, encapsulating fields (health
, armor
, stamina
) and methods (ReceiveDamage
, ShieldHit
, RestoreHealth
).
File content for player/player.go
:
File content for main.go
:
Here, player
is an instance of the Player
struct with methods you can call to manipulate its state.
In Go, access control is managed through capitalization. An identifier, such as a field or method, is exported (similar to "public") if it begins with an uppercase letter. Conversely, if it starts with a lowercase letter, it remains unexported (similar to "private"). Note that this access control is enforced only across package boundaries.
File content for privacy/privacy.go
:
File content for main.go
:
Private-like access to struct fields in Go is controlled by making struct fields unexported, limiting outside interference and ensuring data integrity. Let's consider a BankAccount
use case and let's see how we can implement this.
File content for bankaccount/bankaccount.go
:
File content for main.go
:
Here, balance
is kept unexported, safeguarding the account's integrity.
Private-like methods in Go are handled through naming conventions. Methods beginning with a lowercase letter are unexported and can't be accessed outside their package.
File content for bankaccount/bankaccount.go
:
File content for main.go
:
Here, AddYearlyInterest
is an exported method that calls the unexported method addInterest
.
Fantastic work exploring Go's approach to encapsulation through capitalization conventions of struct fields and methods! By understanding and applying these key principles across package boundaries, your Go code becomes robust, secure, and maintainable.
Next, let’s put these concepts into practice. Get ready for some hands-on exercises to solidify what you've learned! Keep coding — exciting challenges await!
