当前位置:网站首页>How to import a Golang external package and use it?
How to import a Golang external package and use it?
2022-07-31 22:45:00 【HUAWEI CLOUD】
前言
Sometimes your code needs additional functionality outside of the current program.在这些情况下,You can use the bag to make your program more complicated.A package represents all files in a single directory on disk.Packages can define what you can do in other Go Functions referenced in files or packages、类型和接口.
We can by calling various package or library functions in the complex program can do some useful things. Golang 也不例外.在这篇文章中,We will learn how to import in our program Golang 外部包.
标准库
Go The standard library that comes with it is a set of collections.These standard libraries contain many of the basic building blocks for writing modern software.例如, fmt package contains basic functions for formatting and printing strings. net/http Package contains allow developers to create Web 服务、通过 http Protocols for sending and retrieving data, etc..
To use the function of package,您需要使用 import Statement Access Package.import statement by import Composed of keywords and package names.
例如,我们可以通过导入 math/rand package to generate a random number:
import "math/rand"当我们导入一个包时,We make it available in our current program as a separate namespace.This means we have to use dot notation to refer to functions,就像在 package.function 中一样.
在实践中,math/rand A function in a package might look like the following example:
rand.Int()Call a function that returns a random integerrand.Intn()call this function to return the 0 to a random element of the specified number provided
让我们创建一个 for loop to show how random.go 程序中调用 math/rand 包的函数:
package mainimport "math/rand"func main() { for i := 0; i < 10; i++ { println(rand.Intn(30)) }}The program is first imported on the third line math/rand 包,然后进入一个 for 循环,The loop will run 10 次.在循环中,The program will print a 0 到 30 范围内的随机整数.整数 30 passed as its argument to rand.Intn().
当我们使用 go run random.go 运行程序时,我们将收到 10 random integers as output.because these are random,So you may get different integers each time you run the program.输出将如下所示:
$ go run random.go112717291182520160Integer will never be lower than 0 或高于 30.
当导入多个包时,可以使用 () 创建一个块.by using blocks,You can avoid repeat import keywords in each line.This will make your code looks more clean:
import ( "fmt" "math/rand")In order to use the add-on package,We can now format the output and print out the iterations that generated each random number during the loop:
package mainimport ( "fmt" "math/rand")func main() { for i := 0; i < 10; i++ { fmt.Printf("%d) %d\n", i, rand.Intn(30)) }}在本节中,We learned how to import packages and use them to write more complex programs.到目前为止,We only used packages from the standard library.接下来,Let's see how to install and use packages written by other developers.
安装包
While the standard library comes with many great and useful packages,but they are intentionally designed to be generic rather than specific.This allows the developer to according to their specific requirements in the standard library built his own bag.
Go Toolchain comes with go get 命令.This command allows you to install third-party packages to your local development environment and use them in your program.
当使用 go get 安装第三方包时,It is common for a package to be referenced by its canonical path.The path can also be hosted at GitHub Paths to common projects in code repositories such as.因此,如果要导入 flect 包,You will use the complete specifications of the path:
go get github.com/gobuffalo/flectgo get 工具将在 GitHub Found on the package,and install it to your $GOPATH 中.
对于此示例,The code will be installed in this directory:
$GOPATH/src/github.com/gobuffalo/flectThe original author frequently updates the package to fix bugs or add new features.发生这种情况时,You may want to use the latest version of the package to take advantage of new features or resolved bugs.To update the package,可以在 go get 命令中使用 -u 标志:
go get -u github.com/gobuffalo/flectIf the package is not found locally,This command will also make Go 安装该软件包.如果已经安装,Go Will try to update to the latest version of the package.
go get The command always retrieves the latest version of the available package.但是,For previous versions of packages,may be newer than what you are currently using,and useful for updating in your program.To retrieve the package for that specific version,You need to use a package management tool,例如 Go Modules.
从 Go 1.11 开始,Go Modules To manage to import package version.The topic of package management is beyond the scope of this article,但您可以在 Go Modules GitHub 页面上阅读更多相关信息.
The alias way to import packages
If your local package is already named the same as the 3rd party package you are using,You may need to change the package name.发生这种情况时,Aliasing your imports is the best way to handle conflicts.You can modify this by adding an alias in front of the imported package Go The name of the package and its function.
The statement is constructed as follows:
import another_name "package"本例中,修改 random.go 程序文件中 fmt 包的名称.我们将 fmt Change the package name to f to abbreviate.Our modified program will look like this:
package mainimport ( f "fmt" "math/rand")func main() { for i := 0; i < 10; i++ { f.Printf("%d) %d\n", i, rand.Intn(25)) }}在程序中,我们现在将 Printf 函数称为 f.Printf 而不是 fmt.Printf.
While other languages tend to alias packages for later use in the program,但 Go 不喜欢.例如,将 fmt 包别名为 f inconsistent with style guide.
When renaming imports to avoid name clashes,You should aim to rename the most local or project specific imports.例如,如果您有一个名为 strings the local package,and you also need to import the file named strings 的系统包,then you are more inclined to rename local packages rather than system packages.只要有可能,It is advisable to avoid name collisions completely.
在本节中,We learned how to alias an import to avoid conflict with another import in the program.It's important to remember that program readability and clarity are important,So you should only use aliases to make code more readable or need to avoid naming conflicts.
format import
Import by formatting,You can sort packages into a specific order,This will make your code more consistent.此外,When the only thing that changes is the sort order of imports,This will prevent random commits from happening.Since formatting the import will prevent random commits,This will prevent unnecessary code churn and messy code reviews.
Most editors will automatically format the import for you,or lets you configure your editor to use goimports.在编辑器中使用 goimports 被认为是标准做法,Because trying to manually maintain the sort order of imports can be tedious and error prone.此外,If any style changes were made,goimports Will update to reflect these style changes.This ensures that you and anyone working on your code have consistent styles in your import blocks.
This is what the example import block looks like before formatting:
import ( "fmt" "os" "github.com/digital/ocean/godo" "github.com/sammy/foo" "math/rand" "github.com/sammy/bar")运行 goimport 工具(or use most editors that have it installed,saving the file will run it for you),You will now have the following format:
import ( "fmt" "math/rand" "os" "github.com/sammy/foo" "github.com/sammy/bar" "github.com/digital/ocean/godo")请注意,It first groups all the standard library packages together,Then combine the 3rd party package with a blank line.This makes it easier to read and understand the package being used.
在本节中,我们了解到使用 goimports will keep all our import blocks properly formatted,and prevent unnecessary code changes between developers working on the same files.
总结
when we import the package,我们可以调用 Go There is no built-in function in.Some packages come with Go With part of the installation of the standard library,some we will pass go get 安装.
when leveraging existing code,Using packages can make our programs more robust and powerful.We can also create our own packages for ourselves and other programmers,for use in future programs.
参考链接:https://www.digitalocean.com/community/tutorials/importing-packages-in-go
边栏推荐
- Commonly used security penetration testing tools (penetration testing tools)
- Components of TypeScript
- Go1.18 upgrade function - Fuzz test from scratch in Go language
- Implementing a Simple Framework for Managing Object Information Using Reflection
- "APIO2010" Patrol Problem Solution
- 关注!海泰方圆加入《个人信息保护自律公约》
- A high-quality WordPress download site template theme developed abroad
- What is Thymeleaf?How to use.
- AI automatic code writing plugin Copilot (co-pilot)
- 嵌入式开发没有激情了,正常吗?
猜你喜欢

Pytest初体验

VOT2021 game introduction

如何减少软件设计和实现之间鸿沟

Unity-通过预制件和克隆方法动态实现各个UGUI下控件的创建和显示

二叉树非递归遍历

Efficient Concurrency: A Detailed Explanation of Synchornized's Lock Optimization

Qualcomm cDSP simple programming example (to query Qualcomm cDSP usage, signature), RK3588 npu usage query

Structure of the actual combat battalion module eight operations

Implementation of a sequence table

Pytest first experience
随机推荐
Financial profitability and solvency indicators
The uniapp applet checks and prompts for updates
Implementation of a sequence table
Flex layout in detail
Unity - by casting and cloning method dynamic control under various UGUI create and display
无状态与有状态的区别
Binary tree non-recursive traversal
BM3 将链表中的节点每k个一组翻转
数据分析(一)——matplotlib
C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
Efficient Concurrency: A Detailed Explanation of Synchornized's Lock Optimization
The old music player WinAmp released version 5.9 RC1: migrated to VS 2019, completely rebuilt, compatible with Win11
SQL27 View user details of different age groups
【ACM】2022.7.31训练赛
NVIDIA已经开始测试AD106和AD107 GPU核心的显卡产品
BOW/DOM (top)
网易云信圈组上线实时互动频道,「破冰」弱关系社交
Fixed-length usage of nanopb string type based on RT1052 Aworks (27)
C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
老牌音乐播放器 WinAmp 发布 5.9 RC1 版:迁移到 VS 2019 完全重建,兼容 Win11