0%

go环境搭建

环境搭建

  • 打开官网,下载win平台下的msi安装文件,环境变量设置E:\app\Go\bin

  • 本地新建目录,E:\proj\gowork作为工作空间

  • 初始化项目

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/

  • 下载并打开Visual Studio Code,作为开发go的工具,扩展中安装GO
  • 按快捷键ctrl+shift+x,打开扩展,安装GO和chinese

image-20230525113031586

  • 安装go tools的依赖插件
1
2
go env -w GO111MODULE=on
go env -w GOPROXY=https://proxy.golang.com.cn,direct
  • Ctrl+Shift+P 然后搜索>Go:Install/Update Tools 然后勾选全部项目即可。

image-20230525114744401

实践

  • 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 // indirect
)

源码分析

image-20230531170143420

  • hello_wrok/main.go
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自动导入依赖包

  • hello_work/hello.go
1
2
3
4
5
6
7
8
package main

import "fmt"

func Print_hello() {
fmt.Println("Print_hello!")
}

  • hello_work/util/work.go
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!

基础语法

总结