Encapsulation

Golang provides encapsulation at the package level. Go doesn’t have any public, private or protected keyword. The only mechanism to control the visibility is using the capitalized and non-capitalized formats

Capitalized Identifiers are exported. The capital letter indicates that this is an exported identifier. Non-capitalized identifiers are not exported. The lowercase indicates that the identifier is not exported and will only be accessed from within the same package.

There are five kinds of identifier which can be exported or non-exported.

1. Export Struct

package company type PublicCompany struct { Name string address string } type privateCompany struct { name string address string }

Here, in company package, the struct PublicCompany is exported, struct privateCompany is non-exported.

2. Export structure method

package person type Person struct { age int name string } func (person *Person) GetAge() int { return person.age } func (person *Person) getName() string { return person.name }

The Person struct’s method GetAge() is exported and getName is not exported.

3. Export structure field

package student type Student struct { Name string age int }

The Student struct field Name is exported. The Student struct field age is not exported.

4. Export function

package MathTools func Sum(nums ...int) int { var s int = 0 for _, num := range nums { s += num } return s } func average(nums ...int) int { if len(nums) <= 0 { return 0 } return Sum(nums...) / len(nums) } println Sum(1, 2, 3), average(1, 2, 3) println Sum(1, 2, 3)

The function Sum is exported, and the function average is not exported.

5. Export variable

package vars var ( PersonName = "Wang yang" personAge = 21 )

The variable PersonName is exported, and the variable personAge is not exported.

Next example: Interfaces