SoFunction
Updated on 2025-03-03

Detailed explanation of how to import and use packages in go language

introduction

In Go, packages are how code is organized. Each Go program is composed of a package, and the program starts from the main package.

Import package

useimportKeywords can be imported into packages. The imported package can be a package in the Go standard library, a third-party package, or a package you wrote yourself. The following is an import from the standard libraryfmtBaohemathPackage example:

import (
    "fmt"
    "math"
)

In the above code, we importedfmtandmathTwo packages, and then you can use the exposed (exported) functions, types and variables of these two packages in your code.

User package

Use functions, types, or variables in a package and you need to prefix the package name. For example, we can usefmtPackedPrintlnFunctions to output a line of text:

("Hello, world!")

We can also usemathPackedPiVariables:

("Value of Pi is:", )

Import custom packages

You can also create your own packages and import them elsewhere. Suppose we have a package directory structure as follows:

myproject/
|-- 
|-- 
|-- mathext/
    |-- 

existmathext/In  , we have a custom package:

package mathext
// Add adds two integers.
func Add(a, b int) int {
    return a + b
}

existIn, we can import and use this custom package:

package main
import (
    "fmt"
    "myproject/mathext"
)
func main() {
    sum := (1, 2)
    ("The sum is", sum)  // Outputs: The sum is 3
}

Note that when importing custom packages, the path is relative to the module path of Go Modules.

Go Modules

Since Go version 1.11, Go language has introduced the official package management tool Go Modules. Import paths for managing dependent versions and packages.

You can usego mod init [module-path]Command to initialize a new module and create adocument.

For example, if you aremyprojectRun in the directorygo mod init /yourusername/myproject,So/yourusername/myprojectIt is the module path of your project, your custom packagemathextThe import path is/yourusername/myproject/mathext

Summarize

Go's package management provides a simple and powerful way to organize and reuse code. Understanding how to import and use packages is an important step in learning Go.

The above is the detailed explanation of the example of how to import and use packages in Go. For more information about importing and using packages in Go, please pay attention to my other related articles!