Back to Gotraining

README

topics/go/language/exporting/README.md

latest2.7 KB
Original Source

Exporting

Packages contain the basic unit of compiled code. They define a scope for the identifiers that are declared within them. Exporting is not the same as public and private semantics in other languages. But exporting is how we provide encapsulation in Go.

Notes

  • Code in go is compiled into packages and then linked together.
  • Identifiers are exported (or remain unexported) based on letter-case.
  • We import packages to access exported identifiers.
  • Any package can use a value of an unexported type, but this is annoying to use.

Exported/Unexported Identifiers In Go - William Kennedy

Code Review

Declare and access exported identifiers - Pkg (Go Playground)
Declare and access exported identifiers - Main (Go Playground)

Declare unexported identifiers and restrictions - Pkg (Go Playground)
Declare unexported identifiers and restrictions - Main (Go Playground)

Access values of unexported identifiers - Pkg (Go Playground)
Access values of unexported identifiers - Main (Go Playground)

Unexported struct type fields - Pkg (Go Playground)
Unexported struct type fields - Main (Go Playground)

Unexported embedded types - Pkg (Go Playground)
Unexported embedded types - Main (Go Playground)

Exercises

Exercise 1

Part A Create a package named toy with a single exported struct type named Toy. Add the exported fields Name and Weight. Then add two unexported fields named onHand and sold. Declare a factory function called New to create values of type toy and accept parameters for the exported fields. Then declare methods that return and update values for the unexported fields.

Part B Create a program that imports the toy package. Use the New function to create a value of type toy. Then use the methods to set the counts and display the field values of that toy value.

Template | Answer


All material is licensed under the Apache License Version 2.0, January 2004.