Junior
How is encapsulation implemented in Golang?
sobes.tech AI
Answer from AI
Encapsulation in Golang is implemented through controlling the visibility of identifiers (such as variables, functions, structures, methods, packages) at the package level.
- Private: Identifiers whose names start with a lowercase letter are visible only within the package in which they are declared.
package mypackage type myStruct struct { // private structure privateField int // private field PublicField string // public field } func privateFunc() { // private function // ... } func PublicFunc() { // public function // ... } - Public: Identifiers whose names start with an uppercase letter are visible outside the package in which they are declared. They can be accessed from other packages by importing and using the package name.
package anotherpackage import "mypackage" func useStruct() { // mypackage.privateFunc() // Error: private // var s mypackage.myStruct // Error: private structure var sPublic mypackage.MyPublicStruct // Accessible if MyPublicStruct is public sPublic.PublicField = "accessible" // sPublic.privateField = 10 // Error: private field mypackage.PublicFunc() // Accessible }
Encapsulation is achieved by hiding implementation details (private identifiers) from external use, and interaction with the object is only through its public interface (public identifiers). This allows internal implementation to be changed without the need to modify code that uses this package externally, provided the public interface remains the same.
Golang does not have keywords public, private, or protected as in some other languages. Access control is solely based on the case of the first letter of the identifier.