In Go, function visibility is controlled by capitalization in the function name. This convention is part of Go's package system and applies not just to functions, but to all identifiers (such as types, variables, and constants).
Here’s how visibility works:
1. Exported (Public) Functions
- If a function name starts with an uppercase letter, it is exported and accessible from other packages.
- Exported functions can be thought of as “public” functions in other languages; they’re meant to be accessed outside the package where they’re defined.
package mypackage
// ExportedFunction is accessible outside of mypackage
func ExportedFunction() {
fmt.Println("This is an exported function.")
}To use ExportedFunction from another package:
import "mypackage"
func main() {
mypackage.ExportedFunction() // Accessible because it's exported
}2. Unexported (Private) Functions
- If a function name starts with a lowercase letter, it is unexported and only accessible within the same package.
- Unexported functions can be thought of as “private” functions. They are used only within the package where they are defined, typically to implement internal logic or helper functions.
package mypackage
// unexportedFunction is only accessible within mypackage
func unexportedFunction() {
fmt.Println("This is an unexported function.")
}Trying to access unexportedFunction from outside mypackage will result in a compilation error.
3. Practical Usage
- Exported functions provide public-facing APIs for packages, exposing only necessary functionality.
- Unexported functions allow developers to organize code and keep implementation details hidden from other packages, ensuring better encapsulation and reducing coupling.
Example of Both in a Package
package mypackage
// ExportedFunction is visible to other packages.
func ExportedFunction() {
unexportedHelper() // Calling the private function within the same package
fmt.Println("This is a public function.")
}
// unexportedHelper is only accessible within the same package.
func unexportedHelper() {
fmt.Println("This is a private function.")
}In this example:
ExportedFunctionis the API function that other packages can call.unexportedHelperis an internal helper function, used to supportExportedFunctionbut hidden from other packages.
Summary
Capitalization Visibility Usability Uppercase Exported (Public) Accessible by other packages Lowercase Unexported (Private) Accessible only within the same package