In Go, a package is a way to organize and encapsulate code. Packages help you structure your application into reusable and maintainable components. Go packages can contain functions, variables, constants, and types, and they provide a level of visibility control (public and private scope) based on naming conventions.
Here are some key points about Go packages:
Standard Library Packages: Go provides a rich set of standard library packages, like
fmt
,net/http
,os
, andmath
, among others.Custom Packages: You can create your own packages to modularize your code.
Importing Packages: Packages are imported using the
import
keyword. Multiple packages can be imported by enclosing them in parentheses.Package Initialization: When a package is imported, all its
init
functions are called (in the order they appear), and all global variables are initialized.Visibility: If an identifier (function, variable, or type name) starts with an uppercase letter, it is exported (public). Otherwise, it's unexported (private to the package).
Package Alias: When importing a package, you can give it an alias, which can be useful for avoiding name conflicts or shortening long package names.
Package Main: Every executable Go application must contain a
main
package and amain()
function as the entry point.
Workshop Exercise: Test the Concept
For this exercise, we'll create a simple Go project to explore packages. Specifically, we'll build a main package and a custom package, and then import the custom package into the main package.
Create the directory structure
mkdir -p go_packages_demo/mycalculator
Write the custom package
Navigate into the
mycalculator
directory and create a file calledcalculator.go
.// mycalculator/calculator.go package mycalculator // Add returns the sum of two integers. func Add(a int, b int) int { return a + b } // Subtract returns the result of a - b. func Subtract(a int, b int) int { return a - b }
Write the main package
Navigate back to
go_packages_demo
directory and create a file calledmain.go
.package main import ( "fmt" "go_packages_demo/mycalculator" ) func main() { sum := mycalculator.Add(5, 3) difference := mycalculator.Subtract(10, 4) fmt.Printf("Sum: %d\n", sum) fmt.Printf("Difference: %d\n", difference) }
Initialize a Go Module
go mod init go_packages_demo
This will create a
go.mod
file in the project directory.Now, the import path "go_packages_demo/mycalculator" is relative to the root of the Go module, which is
go_packages_demo
.Run the Code
Navigate back to the
go_packages_demo
directory and run:go run main.go
You should see the following output:
Sum: 8 Difference: 6
In this exercise, we created a custom package named mycalculator
with Add
and Subtract
functions. Then, we imported this package into our main
package and used the Add
and Subtract
functions.
This is a very simple example, but it should give you an idea of how Go packages can be used to organize and modularize your code.