Junior — Middle
How is the principle of encapsulation achieved in Go using structures?
sobes.tech AI
Answer from AI
In Go, encapsulation is achieved through identifier visibility rules based on the case of the first letter:
- Names starting with an uppercase letter are exported and accessible from other packages (public).
- Names starting with a lowercase letter are unexported and only accessible within the same package (private).
Thus, to hide fields or methods from outside access, their names are made lowercase.
Example:
package user
type User struct {
name string // private field
Age int // public field
}
func (u *User) GetName() string { // public method
return u.name
}
In this example, the name field is hidden from the outside world, and access to it is provided through the public method GetName(). This implements encapsulation by controlling access to internal data.