Sobes.tech
Junior — Middle

How is encapsulation and hiding of internal data state ensured in the Go language?

sobes.tech AI

Answer from AI

In the Go language, encapsulation and hiding of internal data state are achieved through the rule of exporting identifiers: if the name of a variable, function, method, or struct field begins with an uppercase letter, it is exported (accessible from other packages); if it begins with a lowercase letter, it is private (accessible only within the package).

For example:

package user

type User struct {
    name string // private field
    Age  int    // exported field
}

func NewUser(name string, age int) *User {
    return &User{name: name, Age: age}
}

func (u *User) GetName() string {
    return u.name
}

Here, the name field is hidden from external access, but access to it can be obtained through the GetName() method. Thus, Go uses package-level visibility and naming conventions for encapsulation.

How is encapsulation and hiding of internal data… - sobes.tech