lightsing
lightsing

Reputation: 280

Golang OOP information hiding practice

What can I do with Go struct to hide information? Go struct member is visible to all. How to hide a member in a package?

Upvotes: 3

Views: 1375

Answers (1)

Himanshu
Himanshu

Reputation: 12675

Go is not an Object oriented language. But it encapsulates things at the package level.

According to GoLang specification;-

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

If you don't wants to make your struct variables public do not export them. use lowercase to create variables in a struct type. Unexported struct fields are only accessible to same package.

// unexported struct
type person struct {
    name string // unexported fields can be used only in the same package
    age  int
}

Only package level granularity is allowed in Go. One can declare struct in different package which can be used in those files wherever it is required

Upvotes: 3

Related Questions