Package and import in Go
In Go, a package is a collection of related Go source files that are compiled and stored together as a unit. Go programs are made up of one or more packages, and each package can be used by other packages.
To use a package in your Go code, you need to import it using the import
keyword. For example, to import the fmt
package, which contains functions for formatting and printing text, you would use the following import statement:
import "fmt"
You can then use the functions in the fmt
package by prefixing them with the package name, like this:
fmt.Println("Hello, world!")
You can also import multiple packages at once using a single import statement:
import (
"fmt"
"math"
)
You can also give a package an alias by using the as
keyword:
import (
f "fmt"
m "math"
)
This allows you to use the short alias instead of the full package name when calling functions from the package. For example:
f.Println("Hello, world!")
m.Sqrt(4)
You can also use the _
character as an alias to import a package without using it directly in your code. This is often used to import a package only for its side effects, such as initializing variables or setting up logging. For example:
import _ "github.com/my/package"