Import Basics
Understanding Package Imports in Go
In Go programming, package imports are fundamental to organizing and reusing code. When you want to use functionality from another package, you need to import it using the import
keyword.
Basic Import Syntax
A standard package import looks like this:
import "package/path"
For example, to import the standard fmt
package:
import "fmt"
func main() {
fmt.Println("Hello, LabEx!")
}
Multiple Package Imports
Go allows you to import multiple packages in different ways:
Single-Line Imports
import "fmt"
import "math"
Grouped Imports
import (
"fmt"
"math"
"strings"
)
Import Paths
Go packages are identified by their full import path, which typically follows the repository structure:
graph TD
A[Module Root] --> B[Package 1]
A --> C[Package 2]
B --> D[Subpackage]
Import Type |
Example |
Description |
Standard Library |
"fmt" |
Built-in Go packages |
External Packages |
"github.com/user/repo" |
Packages from external repositories |
Local Packages |
"./mypackage" |
Packages in your project |
Initialization
When a package is imported, its init()
function is automatically called before the main()
function, allowing for package-level setup.
package main
import "fmt"
func init() {
fmt.Println("Package initialized")
}
func main() {
fmt.Println("Main function")
}
Key Takeaways
- Imports are essential for code organization
- Multiple import styles are supported
- Packages can be from standard library, external sources, or local projects
- Import paths reflect the package's location
By understanding these import basics, you'll be well-prepared to explore more advanced import techniques in Go, including import aliases, which we'll cover in the next section.