环境搭建
1 2 3 4 5 6 7 8 9
| cd E:\proj\gowork mkdir hello_work cd hello_work go mod init example.com/hello_work
$ go mod init example.com/hello_work go: creating new go.mod: module example.com/hello_work go: to add module requirements and sums: go mod tidy
|
go mod tidy 执行后,把当前项目中不需要用的依赖文件删除,也就是go.mod中添加的依赖文件
1 2 3 4
| Administrator@WIN-5TF67LA12I4 MINGW64 /e/proj/gowork $ ls go.mod hello_work/
|

1 2
| go env -w GO111MODULE=on go env -w GOPROXY=https:
|
- 按
Ctrl+Shift+P
然后搜索>Go:Install/Update Tools
然后勾选全部项目即可。

实践
- vscode 打开
E:\proj\gowork
目录
- 在终端中拉取远程的依赖项目代码:
go get github.com/georgehao/gomodtestc
- 拉取远程代码成功后,
go.mod
文件中生产的代码如下
1 2 3 4 5 6 7 8
| module example.com/hello_work
go 1.20
require ( github.com/georgehao/gomodtestc v1.0.1 )
|
源码分析

1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package main
import ( "fmt"
"example.com/hello_work/hello_work/util" // 引用本地其他目录下的文件 "github.com/georgehao/gomodtestc" // 引用远程项目地址 )
func main() { fmt.Println(gomodtestc.PrintStr("Hello", 100)) // 调用远程项目的代码 Print_hello() // 相同文件夹内的函数直接调用,来自于代码hello.go util.Print_work() //util是包名 }
|
在编写代码中,比如输入Print_hello,import自动导入依赖包
1 2 3 4 5 6 7 8
| package main
import "fmt"
func Print_hello() { fmt.Println("Print_hello!") }
|
1 2 3 4 5 6 7 8 9 10 11 12
| package util
import "fmt"
func init() { fmt.Println("imp-init() come here.") }
func Print_work() { fmt.Println("Hello!") }
|
- 执行命令,如下go run 执行了两个go文件,因为不这样执行无法调用到hello.go中的函数,理论上根目录下只有一个main.go函数,其他函数写到其他目录下
1 2 3 4 5
| PS E:\proj\gowork> go run .\hello_work\main.go .\hello_work\hello.go imp-init() come here. project C Hello_100 Print_hello! Hello!
|
基础语法

总结