作为一名Gopher,可能都很想从源码级别去熟悉了解Go,但对于初学者,这可能有点障碍,因为go源码打开后,不能使用go run运行代码也不能进行调试,本文就是为了打破这个障碍,扫清我们学习Go自身源码的挡路石。
准备
-  克隆Go源码 jagitch@34c4dd4d4a3e:opensource$ git clone https://github.com/golang/go.git Cloning into 'go'... remote: Enumerating objects: 615933, done. remote: Counting objects: 100% (22992/22992), done. remote: Compressing objects: 100% (846/846), done. remote: Total 615933 (delta 22421), reused 22171 (delta 22146), pack-reused 592941 Receiving objects: 100% (615933/615933), 343.05 MiB | 1.33 MiB/s, done. Resolving deltas: 100% (489881/489881), done. Updating files: 100% (13308/13308), done.- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
 如果github克隆很慢或存在网络问题,请参考github无法访问克隆不了项目下载失败没反映的解决方法 
-  如果vscode没有安装Go扩展,请安装 
问题
如果不进行任何配置,打开Go源码项目后很多代码会爆红,调试时也会报错,如果安装的go版本低于Go源码也会出现问题。

解决方法:
-  切换git仓库到需要调试的go版本,此处以go1.22.3版本为例,go的版本可以通过 git tag查看jagitch@34c4dd4d4a3e:go$ git checkout -b go1.22.3.study go1.22.3 Switched to a new branch 'go1.22.3.study' jagitch@34c4dd4d4a3e:go$ git branch * go1.22.3.study master- 1
- 2
- 3
- 4
- 5
- 6
 
-  进入到go源码的src目录 jagitch@34c4dd4d4a3e:go$ cd src- 1
 
-  执行 make.bash,从源码构建go1.22.3jagitch@34c4dd4d4a3e:src$ . ./make.bash Building Go cmd/dist using /usr/local/go. (go1.22.2 linux/amd64) Building Go toolchain1 using /usr/local/go. Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1. Building Go toolchain2 using go_bootstrap and Go toolchain1. Building Go toolchain3 using go_bootstrap and Go toolchain2. Building packages and commands for linux/amd64. --- Installed Go for linux/amd64 in /home/coder/workspace/opensource/go Installed commands in /home/coder/workspace/opensource/go/bin *** You need to add /home/coder/workspace/opensource/go/bin to your PATH.- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
 
-  查看go路径和版本 jagitch@34c4dd4d4a3e:src$ which go /home/coder/workspace/opensource/go/bin/go jagitch@34c4dd4d4a3e:src$ go version go version go1.22.3 linux/amd64- 1
- 2
- 3
- 4
 此时已编译好指定的go1.22.3这个版本了 
-  在vscode中打开项目,然后打开命令面板,输入 go choose搜索然后点击Go: Choose Go Environment 选择当前Go源码目录下编译的 go可执行程序,如果没有,则关闭vscode,重新打开vscode。
  
-  到目前为止,就已经可以运行和调试go源码,这里以 src/cmd/compile/main.go为例进行演示 
-  直接运行main.go jagitch@34c4dd4d4a3e:go$ cd src/cmd/compile/ jagitch@34c4dd4d4a3e:compile$ go run main.go -V I'm debugging with the source code of go main version go1.22.3 jagitch@34c4dd4d4a3e:compile$ which go /home/coder/workspace/opensource/go/bin/go- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
 
-  如果需要全局使用此次编译的go版本,则将它配置到PATH环境变量中即可(配置到~/.bashrc) jagitch@34c4dd4d4a3e:compile$ echo 'export /home/coder/workspace/opensource/go/bin' >> ~/.bashrc jagitch@34c4dd4d4a3e:compile$ source ~/.bashrc- 1
- 2
- 3
 
-  如果是用于学习Go源码,建议搭建浏览器版的vscode,这样就可以使用手机和平板打开浏览器随时浏览Go语言,并且拥有vscode中所有功能,可以转到代码定义,可以进行调试,很方便。可以参考搭建Golang在线开发环境(随时随地码代码) 
推荐阅读
1. github无法访问克隆不了项目下载失败没反映的解决方法
 2. Vs code调试Go程序时怎样查看CPU寄存器的值
 3. 搭建Golang在线开发环境(随时随地码代码)
 
                                    
评论记录:
回复评论: