Go Lang - Packages and Imports
Working with Packages and Imports in Go
This guide provides examples and explanations of working with packages and imports in the Go programming language.
Key Points:
- Go uses packages to organize code into reusable units, with each package containing related functions, types, and variables.
- Imports in Go allow you to use code from other packages, making it easy to leverage existing functionality.
- Go standard library provides a rich set of packages for common tasks, and you can also create your own packages for modularizing your code.
Importing Packages
You can import packages in Go using the import
keyword followed by the package path.
// Example: Importing packages in Go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Random number:", rand.Intn(100))
}
Creating and Using Custom Packages
You can create your own packages in Go to organize and reuse your code across multiple files or projects.
// Example: Creating and using custom packages in Go
// File: math_operations.go
package math_operations
import "fmt"
func Add(a, b int) int {
return a + b
}
func Subtract(a, b int) int {
return a - b
}
// File: main.go
package main
import (
"fmt"
"yourmodule/math_operations"
)
func main() {
result := math_operations.Add(5, 3)
fmt.Println("Addition result:", result)
}
Summary
This guide provided examples and explanations of working with packages and imports in Go, including importing standard library packages, creating custom packages, and using imported functions. By mastering these concepts, you can effectively organize and reuse code in your Go projects.