Packages are a way to organize and structure your code into reusable and manageable units. A package consists of one or more Go source files grouped together in a directory. Each file in the package can contain functions, variables, types, and other declarations.
Packages serve multiple purposes:
Modularity: Packages allow you to break your code into smaller, self-contained pieces, promoting code reusability and maintainability.
Name Space: Packages provide a way to prevent naming conflicts between different identifiers in your code.
Organization: By separating functionality into packages, your codebase becomes more organized and easier to navigate.
Creating Your Own Package:
To create your own package, you need to follow a few guidelines:
Place the related '.go' files in the same directory.
Add a 'package' declaration at the beginning of each file.
Use proper naming conventions (lowercase for package names, CamelCase for exported functions/types).
For example, consider a simple package named 'math':
// math.go package math
func Add(a, b int) int { return a + b }
func Subtract(a, b int) int { return a - b }
Using Packages:
To use functions and types from a package, you need to import it into your code. The 'import' keyword is used for this purpose.
Example of Importing and Using a Package:
package main
import ( "fmt" "myapp/math" // Importing the custom math package )
You can use aliases to simplify the package name within your code.
package main
import (
"fmt"
m "myapp/math" // Alias "m" for the custom math package
)
func main() {
result := m.Add(5, 3)
fmt.Println(result) // Output: 8
}
Using Standard Library Packages:
Go provides a rich standard library that includes many useful packages. You can use these packages by directly importing them.
Example of Using a Standard Library Package:
package main
import ( "fmt" "strings" // Importing the strings package from the standard library )
Go enforces a specific directory structure where each package should reside in its own directory. The directory name should match the package name. For example, a package named 'mypackage' should be in a directory named 'mypackage'.
By understanding how packages work and how to import and use them, you can structure your codebase efficiently, promote code reuse, and keep your codebase organized and maintainable.