Go Packages
Understanding Go's package system for code organization
📦 What are Go Packages?
Go packages are collections of related Go source files that work together. Every Go program is made up of packages, helping organize and reuse code efficiently across projects.
// This is a simple Go package example
package main
import "fmt"
func main() {
fmt.Println("Hello from Go package!")
}
Output:
Hello from Go package!
Key Package Concepts
Package Declaration
Every Go file starts with a package declaration
package main
Main Package
Special package that creates executable programs
package main
func main() {
// Entry point
}
Custom Packages
Create your own packages for code organization
package utils
func Helper() string {
return "Helper function"
}
Visibility
Uppercase names are exported (public)
// Exported
func PublicFunc() {}
// Not exported
func privateFunc() {}
🔹 Creating a Simple Package
Here's how to create and use a custom package:
📁 File: math/calculator.go
package math
// Add two numbers (exported function)
func Add(a, b int) int {
return a + b
}
// Subtract two numbers (exported function)
func Subtract(a, b int) int {
return a - b
}
// helper function (not exported)
func validate(n int) bool {
return n >= 0
}
📁 File: main.go
package main
import (
"fmt"
"./math" // Import our custom package
)
func main() {
result1 := math.Add(10, 5)
result2 := math.Subtract(10, 3)
fmt.Printf("10 + 5 = %d\n", result1)
fmt.Printf("10 - 3 = %d\n", result2)
}
Output:
10 + 5 = 15
10 - 3 = 7
🔹 Package Naming Rules
Follow these conventions when naming packages:
- Lowercase: Package names should be lowercase
- Short: Use short, descriptive names
- No underscores: Avoid underscores in package names
- Descriptive: Name should describe what the package does
// Good package names
package http
package json
package strings
package database
// Avoid these
package HTTP // Don't use uppercase
package string_utils // Don't use underscores
package pkg // Too generic
🔹 Package Structure Example
Organize your Go project with proper package structure:
// Project structure:
// myproject/
// ├── main.go
// ├── handlers/
// │ └── user.go
// └── models/
// └── user.go
// File: handlers/user.go
package handlers
import "fmt"
func GetUser(id int) string {
return fmt.Sprintf("User %d", id)
}
// File: models/user.go
package models
type User struct {
ID int
Name string
}
func NewUser(id int, name string) User {
return User{ID: id, Name: name}
}