Practical Examples
Real-World Package Visibility Scenarios
1. Creating a Configuration Package
package config
// Unexported struct with private fields
type configuration struct {
dbHost string
dbPort int
maxRetries int
}
// Exported function to create configuration
func NewConfig(host string, port int) *configuration {
return &configuration{
dbHost: host,
dbPort: port,
}
}
// Exported method with controlled access
func (c *configuration) GetDBHost() string {
return c.dbHost
}
Package Interaction Diagram
graph TD
A[Main Package] --> B[Config Package]
B --> C[Public Methods]
B --> D[Private Implementation]
2. Library Package Design
package mathutils
// Exported function
func Add(a, b int) int {
return a + b
}
// Unexported helper function
func validateInput(a, b int) bool {
return a > 0 && b > 0
}
// Exported function with internal logic
func SafeAdd(a, b int) (int, error) {
if !validateInput(a, b) {
return 0, fmt.Errorf("invalid input")
}
return Add(a, b), nil
}
Visibility Patterns Comparison
Pattern |
Visibility |
Use Case |
Public Methods |
Exported |
External package access |
Private Helpers |
Unexported |
Internal implementation |
Controlled Access |
Mixed |
Secure data management |
3. Service Package with Encapsulation
package userservice
type User struct {
// Unexported fields
id int
username string
password string
}
// Exported constructor
func NewUser(username, password string) *User {
return &User{
username: username,
password: hashPassword(password),
}
}
// Unexported password hashing
func hashPassword(pwd string) string {
// Secure hashing logic
return hashedPwd
}
// Exported method with controlled access
func (u *User) Authenticate(inputPassword string) bool {
return comparePasswords(u.password, inputPassword)
}
Advanced Visibility Techniques
Package-Level State Management
package counter
var (
// Unexported package-level variable
currentCount int
// Exported package-level variable
MaxCount = 100
)
// Exported function to modify state
func Increment() int {
if currentCount < MaxCount {
currentCount++
}
return currentCount
}
Best Practices Visualization
graph TD
A[Package Design] --> B[Clear Public Interface]
A --> C[Hidden Implementation]
B --> D[Exported Methods]
C --> E[Unexported Helpers]
Key Takeaways
- Use unexported fields for internal state
- Provide controlled access through exported methods
- Design clear and intuitive public interfaces
- Protect sensitive implementation details
By applying these practical examples, developers can create more robust and maintainable Go packages. LabEx encourages exploring these visibility patterns to enhance your Go programming skills.