前言
因本人工作原因,需要从Java转到Go。之前一直没有接触过Go,所以就跟着Go官网过一遍打好基础。
关于怎么安装可以参考官网介绍,一直下一步即可,至于编辑代码工具选择GoLand(因为Java开发之前习惯了)
示例
- 创建目录
- 启用依赖项跟踪
2.1 运行 go mod init命令,生成go.mod文件// day02/hello:所在模块的名称(模块路径--> 在实际开发中,模块路径通常是保存源代码的存储库位置) go mod init awesomeProject/day02/hello
- 创建hello.go文件
3.1 当运行main包时,默认执行main方法package main import "fmt" func main(){ fmt.Println("hello world") }
- 运行代码,观察运行结果
调用外部包的代码
- 在pkg.go.dev搜索外部包(以rsc.io/quote为例)
1.1 在搜索结果中单击该rsc.io/quote包,在Documentation的Index下展示调用的函数列表
- 导入rsc.io/quote包并添加对其Go函数的调用
package main import "fmt" import "rsc.io/quote" func main() { fmt.Println(quote.Go()) }
- 添加新模块的requirements和sums
3.1 执行go mod tidy,有如下报错(貌似因为代理原因访问不了)// 检查依赖 tidy会检测该文件夹目录下所有引入的依赖,写入 go.mod 文件 $ go mod tidy go: finding module for package rsc.io/quote go: found rsc.io/quote in rsc.io/quote v1.5.2
(1)解决方案:go env -w GOPROXY=https://goproxy.cn
3.2 提示下载成功后,下载模块在GOPATH/pkg/mod下C:\Users\zto\go\src\awesomeProject\day02\hello>go mod tidy go: finding module for package rsc.io/quote awesomeProject/day02/hello imports rsc.io/quote: module rsc.io/quote: Get "https://proxy.golang.org/rsc.io/quote/@v/list": dial tcp 172.217.160.81:443: connectex: A connection att empt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has fai led to respond.
(1)虽然下载成功,但是编辑器显示 Cannot resolve file ‘quote’(不影响正常运行)
(2)go mod vendor 导入依赖解决编辑器Cannot resolve file ‘quote’
- 运行代码,查看返回信息
$ go run . // 注意: 这不是错误信息,这是正常返回 Don't communicate by sharing memory, share memory by communicating.
调用本地未发布的模块
- 使用 go mod edit命令将go工具从模块路径(模块不在的位置)重定向到本地目录(模块在的位置)
1.1 执行之后在go.mod文件中生成replace指令go mod edit -replace awesomeProject/day03/greetings=../greetings
1.2 在hello目录下,运行go mod tidy命令同步模块的依赖关系,添加代码所需但尚未在模块中跟踪的那些
编译应用程序
- 在hello目录中执行go build命令将代码编译为可执行文件
C:\Users\zto\go\src\awesomeProject\day03\hello> go build
- 运行hello可执行文件
束语
本篇文章通过示例来感受Go这门语言,然后介绍了如何导入外部包以及如何解决导入遇到的问题
📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!