Working with Packages
Swipe to show menu
You will explore how to structure and organize code using packages in Go. You will learn about visibility rules that determine which functions, types, and variables can be accessed from outside a package.
Visibility in Go Packages
Go uses a simple rule to control visibility of identifiers (such as variables, functions, types, and constants) within packages:
- Exported identifiers: Start with an uppercase letter; can be accessed from other packages;
- Unexported identifiers: Start with a lowercase letter; are private to the current package.
This rule applies to any identifier you define. For example, PrintMessage would be accessible from outside its package, while formatMessage would be hidden from other packages.
Example:
// In package greetings
type Person struct { // exported, accessible from other packages
Name string
}
func SayHello() { // exported
// ...
}
func formatGreeting(name string) string { // unexported, only for use inside 'greetings' package
// ...
}
When using another package, you can only access its exported identifiers. Unexported identifiers are invisible to code outside their package, which helps you control your packageβs public API and prevent unwanted access to internal details.
Organizing Code Across Multiple Files in a Package
When your Go project grows, you often need to split code into several files for clarity and maintainability. In Go, you can organize related code into multiple files within the same package by following these rules:
- Place all related files in the same directory;
- Use the same
packagename at the top of each file; - Only one file in the directory should contain the
main()function if it is an executable package.
By doing this, all files in the directory become part of the same package. This allows you to define functions, types, and variables in separate files, but access them as if they were in one file. For example, you might have math.go and util.go in a calculator package, both starting with package calculator. All exported functions and types are available throughout the package.
This approach keeps your code organized and makes it easier to maintain as your project grows.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat