In Go language, when we need to import a package, we can use import
:
import (
"io"
)
For standard libraries such as bufio
, time
, net
, etc., we can import them with just their names, similar to C language's #include
.
However, when we want to import our own packages or third-party source code, there are some details to pay attention to.
You can use the go env
command to view the default package download storage path.
Current Directory
Aside from main.go
, if we create a new package (.go file) in the current directory or the next level down, we need to use a relative path starting with ./
to import it.
import (
"./my/my"
)
Third-party Source Code
If the source code or package is located in the path specified by GOPATH
, you only need to specify the relative path name.
For example, to use Gin, you need to run the command:
go get -u github.com/gin-gonic/gin
The source code will be stored in the path indicated by GOPATH
.
When using it, you just need to do this:
import (
"github.com/gin-gonic/gin"
)
It is important to note that github.com
, gin-gonic
, and gin
are directory names. They represent a three-level directory structure. You are not importing github.com/gin-gonic/gin
directly.
For example, when the author installed Gin, the directory path is:
E:\go\pkg\mod\github.com\gin-gonic\gin@v1.6.3
文章评论