Basics
Go Packages
Using Go Packages
Go packages organize code with import and package declarations.
Understanding Go Packages
In Go, a package is a collection of source files in the same directory that are compiled together. A package can contain one or more Go source files and is a fundamental way to organize code in a Go application. Packages help in code reuse, separation of concerns, and management of dependencies.
Creating Your First Package
To create a package in Go, you need to follow a few simple steps. First, you must create a directory for your package. The directory name typically reflects the package's purpose or functionality.
// Create a directory for your package
mkdir mypackage
Next, create a Go source file in this directory. At the top of the source file, declare the package name. The package name is usually the same as the directory name.
// File: mypackage/mypackage.go
package mypackage
import "fmt"
func Hello() {
fmt.Println("Hello from mypackage!")
}
Importing Packages
Once you have created a package, you can use it in other Go files by importing it. Use the import
keyword followed by the package path. The package path is typically the directory structure from the src
directory in your GOPATH
or your module root.
// File: main.go
package main
import (
"fmt"
"mypackage"
)
func main() {
fmt.Println("Main package")
mypackage.Hello()
}
Package Visibility and Exported Names
In Go, only identifiers (such as functions, types, and variables) that start with an uppercase letter are exported and can be accessed from other packages. Identifiers with a lowercase first letter are unexported and private to the package.
// File: mypackage/mypackage.go
package mypackage
// Exported function
func Hello() {
fmt.Println("Hello from mypackage!")
}
// Unexported function
func goodbye() {
fmt.Println("Goodbye from mypackage!")
}
In this example, Hello
is accessible from other packages, while goodbye
is not.
Conclusion and Best Practices
When working with Go packages, remember to:
- Use meaningful and concise names for your packages.
- Organize your code logically, grouping related functionalities.
- Keep your package structure simple and avoid cyclic dependencies.
Basics
- Previous
- Security Basics
- Next
- Workspaces