Junior — Middle
Explain the concept of data encapsulation in object-oriented programming.
sobes.tech AI
Answer from AI
Encapsulation is a principle of object-oriented programming that involves hiding the internal state of an object and providing access to it only through methods (interfaces).
In Go, encapsulation is achieved through the visibility of identifiers:
- Names starting with an uppercase letter are exported and accessible from other packages (public).
- Names starting with a lowercase letter are only accessible within the package (private).
Thus, to encapsulate data, you should declare struct fields with lowercase letters and provide methods to access and modify these fields.
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
}
This approach allows controlling access to data, ensuring its integrity, and changing the internal implementation without affecting external code.