Go Encapsulation and Access Control: Mastering Privacy with Naming Conventions
Lesson Overview
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!
Into the Encapsulation
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.
Remark the Privacy
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:
