Junior — Middle
Kuidas realiseeritakse andmete kapseldumise põhimõte programmeerimiskeeles Go?
sobes.tech AI
Vastus AI-lt
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.
To hide data, it is sufficient to make struct fields start with a lowercase letter, and implement methods with an uppercase letter (getters and setters) to access them.
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.