Object orientation in Go – visibility

Managing visibility is key to good class design and, in turn, to the ruggedness of the system. Unlike other object-oriented languages, there are no public or private keywords in Go. A struct field with a lowercase starting letter is private, while if it is in uppercase, then it's public. For example, consider a Pigeon package:

package pigeon

type Pigeon struct { Name string featherLength int }

func (p *Pigeon) GetFeatherLength() int { return p.featherLength }
func (p *Pigeon) SetFeatherLength(length int) { p.featherLength = length }

Here, inside struct we have the following:

  • Name is a public attribute, and the code outside of the package can reference it.
  • featherLength is a private attribute, and the code outside of the package cannot reference it.

The implications of this packaging mean that the following code will not compile (assuming the code is outside of the Pigeon package):

func main() {
     p := pigeon.Pigeon{"Tweety", 10} //This will not compile
}

featherLength is not exposed from the Pigeon package. The right way to instantiate an object of this struct would be to use the setter function provided:

func main() {
     p := pigeon.Pigeon{Name :"Tweety", }
     p.SetFeatherLength(10)
     fmt.Println(p.Name)
     fmt.Println(p.GetFeatherLength())
     //fmt.Println(p.featherLength) - This will not compile
   }

The capitalization-of-initial-letter convention also extends for methods too. Public methods have the first letter capitalized, whereas private ones start with a lowercase character

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset