How to import packages in Go language

青灯夜游
Release: 2023-02-17 14:44:26
Original
2888 people have browsed it

In the Go language, you can import packages through the import statement. The imported package name is surrounded by double quotes. The package name is the path calculated starting from GOPATH, and uses "/" to separate the paths. There are two basic formats for importing packages: 1. Single-line import syntax "import "bao1" import "bao2""; 2. Multi-line import syntax "import("bao1" "bao2" ...)".

How to import packages in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language import import package - using other code in the code

can be used after a Go language source file package declaration statement, Contain zero or more import package declaration statements before other non-import declaration statements. Each import statement can specify an import path individually, or multiple import paths can be imported simultaneously through parentheses. To reference identifiers of other packages, you can use the import keyword. The imported package name is surrounded by double quotes. The package name is the path calculated starting from GOPATH and is separated by /.

Default import writing method

There are two basic formats for import, namely single-line import and multi-line import. The import code effect of the two import methods is the same.

1) Single-line import

The single-line import format is as follows:

import "包1"
import "包2"
Copy after login

2) Multi-line import

When importing multiple lines, the package name is in the import The order does not affect the import effect. The format is as follows:

import(
    "包1"
    "包2"
    …
)
Copy after login

Customize the referenced package name after importing the package

If we want to import both at the same time If there are two packages with the same name, such as math/rand package and crypto/rand package, then the import statement must specify a new package name for at least one package with the same name to avoid conflicts. This is called renaming the imported package.

import (
    "crypto/rand"
    mrand "math/rand" // 将名称替换为mrand避免冲突
)
Copy after login

Renaming of imported packages only affects the current source file. If other source files import the same package, they can use the original default name of the imported package or rename it to another completely different name.

Import package renaming is a useful feature, not just for resolving name conflicts. If the imported package name is unwieldy, especially in some automatically generated code, it may be more convenient to use a short name. When choosing to rename imported packages with short names, it is best to be consistent to avoid confusion in package names. Choosing another package name can also help avoid conflicts with local common variable names. For example, if there is already a variable named path in the file, then we can rename the "path" standard package to pathpkg.

Each import declaration statement clearly specifies the dependency relationship between the current package and the imported package. If you encounter a package import loop, the Go language build tool will report an error.

Anonymous import package - only import the package but do not use the types and values ​​​​in the package

If you only want to import the package without using any When you do not call any functions in the package, you can use anonymous import to import the package. The format is as follows:

import (
    _ "path/to/package"
)
Copy after login

Among them, path/to/package represents the name of the package to be imported, underlined _ means importing the package anonymously.

Anonymously imported packages will be compiled into the executable file just like other imported packages. At the same time, the imported package will also trigger the init() function call.

The initialization entry of the package before the program starts: init

In the design of certain requirements, it is necessary to call the program reference uniformly when the program starts If you need to manually call these initialization functions by developers, errors or omissions may occur in this process. We hope that within the referenced package, the package writer will be notified of the code startup and do some initialization work for the code in his own package when the program starts.

For example, in order to improve the execution efficiency of the math library for calculating trigonometric functions, the values ​​of the trigonometric functions can be built into an index table in memory in advance when the program is started, and the external program can quickly obtain the values ​​of the trigonometric functions by looking up the table. value. However, the call to the initialization function of the trigonometric function index table is not expected to be called by every developer who uses trigonometric functions externally. If there is a mechanism in the trigonometric function package that can tell when the trigonometric function package program starts, then the initialization problem can be solved. question.

The Go language provides a very convenient feature for the above problems: the init() function.

The characteristics of the init() function are as follows:

  • Each source code can use 1 init() function.

  • The init() function will be automatically called before the program is executed (before the main() function is executed).

  • The calling order is for the packages referenced in main(), which are initialized in depth-first order.

For example, assuming there is such a package reference relationship: main→A→B→C, then the init() function calling sequence of these packages is:

C.init→B.init→A.init→main
Copy after login

Explanation :

  • The calling order of multiple init() functions in the same package is unpredictable.

  • init() function cannot be called by other functions.

理解包导入后的init()函数初始化顺序

Go 语言包会从 main 包开始检查其引用的所有包,每个包也可能包含其他的包。Go 编译器由此构建出一个树状的包引用关系,再根据引用顺序决定编译顺序,依次编译这些包的代码。

在运行时,被最后导入的包会最先初始化并调用 init() 函数。

通过下面的代码理解包的初始化顺序。

代码8-3 包导入初始化顺序入口(…/chapter08/pkginit/main.go)

package main
import "chapter08/code8-2/pkg1"
func main() {
    pkg1.ExecPkg1()
}
Copy after login

代码说明如下:

  • 第 3 行,导入 pkg1 包。

  • 第 7 行,调用 pkg1 包的 ExecPkg1() 函数。

代码8-4 包导入初始化顺序pkg1(…/chapter08/pkginit/pkg1/pkg1.go)

package pkg1
import (
    "chapter08/code8-2/pkg2"
    "fmt"
)
func ExecPkg1() {
    fmt.Println("ExecPkg1")
    pkg2.ExecPkg2()
}
func init() {
    fmt.Println("pkg1 init")
}
Copy after login

代码说明如下:

  • 第 4 行,导入 pkg2 包。

  • 第 8 行,声明 ExecPkg1() 函数。

  • 第 12 行,调用 pkg2 包的 ExecPkg2() 函数。

  • 第 15 行,在 pkg1 包初始化时,打印 pkg1 init。

代码8-5 包导入初始化顺序pkg2(…/chapter08/pkginit/pkg2/pkg2.go)

package pkg2
import "fmt"
func ExecPkg2() {
    fmt.Println("ExecPkg2")
}
func init() {
    fmt.Println("pkg2 init")
}
Copy after login

代码说明如下:

  • 第 5 行,声明 ExecPkg2() 函数。

  • 第 10 行,在 pkg2 包初始化时,打印 pkg2 init。

执行代码,输出如下:

pkg2 init
pkg1 init
ExecPkg1
ExecPkg2
Copy after login

【相关推荐:Go视频教程编程教学

The above is the detailed content of How to import packages in Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!