In Go, a package is a fundamental concept for organizing and reusing code. This guide explains everything you need to know about Go packages.
1. Basic Definition
- A package is a collection of source files in the same directory.
- All files in a package must declare the same package name at the top.
- It provides modularity, encapsulation, and code reuse.
2. Types of Packages
a) Main Package
package main - A special package that creates an executable program.
- Must contain a
main()function. - Used only for executables.
b) Library Packages
package myutils - Can have any name except
main. - Used to create reusable code.
- Can be imported by other packages.
3. Package Visibility Rules
- Names starting with an uppercase letter are exported (public).
- Names starting with a lowercase letter are unexported (private).
Example:
package calculator // Public function - accessible outside the package func Add(x, y int) int { return x + y } // Private function - only accessible within this package func multiply(x, y int) int { return x * y } 4. Using Packages
To use packages in Go, you import them:
import ( "fmt" // Standard library package "myapp/mypackage" // Custom package ) 5. Package Organization Example
myapp/ ├── main.go // package main ├── utils/ │ ├── math.go // package utils │ └── strings.go // package utils └── models/ └── user.go // package models 6. Benefits of Using Packages
- Code organization
- Namespace management
- Code reusability
- Encapsulation
- Dependency management
7. Key Takeaways
- All files in the same folder must have the same package name.
- Package names usually match the directory name.
- Standard library packages like
fmt,strings, etc., come with Go installation. - You can create custom packages for better code structure.
- Use
go mod initto initialize a new module (which can contain multiple packages).
By following these best practices, you can effectively manage code in Go using packages.
Top comments (0)