Junior — Middle
How is the principle of data encapsulation implemented in the Go language?
sobes.tech AI
Answer from AI
In Go, encapsulation is achieved through the visibility rule of identifiers: if the name of a variable, function, method, or struct field starts with an uppercase letter, it is exported and accessible from other packages; if it starts with a lowercase letter, it is only accessible within the current package.
Thus, to hide data, it is enough to make struct fields lowercase, and to access them, implement methods with uppercase names (getters and setters).
Example:
package user
type User struct {
name string // private field
}
func NewUser(name string) *User {
return &User{name: name}
}
func (u *User) GetName() string {
return u.name
}
func (u *User) SetName(name string) {
u.name = name
}
}
Here, the name field is hidden from external access, and the GetName and SetName methods provide controlled access to it.