直接装Go SDK并用go mod init初始化项目即可运行练习代码,无需额外工具链;需正确配置GOROOT和PATH环境变量,显式指定模块名,用go run .验证,避免误用go test。
直接装 Go SDK + 用 go mod init 初始化项目就够了,不需要额外工具链或 IDE 插件也能跑通练习代码。
GOROOT 和 PATH
很多「Go 命令未找到」或「cannot find package」问题都源于环境变量没配对。运行以下命令检查:
go version echo $GOROOT echo $PATH | grep -o '/usr/local/go/bin\|~/go/bin'
常见错误现象:
command not found: go → /usr/local/go/bin(macOS/Linux)或 C:\Go\bin(Windows)没加进 PATH
go: cannot find main module → 当前目录不在模块路径下,且没执行过 go mod init
建议做法:
~/.zshrc 或 ~/.bash_profile 中添加 export PATH=$PATH:/usr/local/go/bin
Go\bin 在 PATH 最前面GOROOT,除非你装了多个 Go 版本且用了 gvm 类工具go mod init 创建最小可运行练习项目进入空目录后,go mod init 不只是生成 go.mod,它还决定了包导入路径和依赖解析行为。练习时建议显式指定模块名,避免默认用当前路径导致后续引用出错。
mkdir hello-go && cd hello-go go mod init example.com/hello
接着写一个最简 main.go:
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}
关键点:
example.com/hello)不一定要真实存在,但不能是 main 或空字符串go mod init 直接 go run main.go,Go 会以“无模块模式”运行,无法使用 go get 或管理依赖go.sum 锁定,但一旦加了第三方包(比如 github.com/spf13/cobra),go mod tidy 会自动补全go test 陷阱)初学时容易把 当成运行入口,但它只执行 
*_test.go 文件里的 TestXxx 函数。练习逻辑代码,请坚持用 go run 或 go build。
go run main.go:适合单文件快速验证,不生成二进制go run .:推荐,自动识别当前模块的 main 包(支持多文件)go build -o hello .:生成可执行文件,方便反复运行go test 跑普通代码 → 输出 no tests to run,不是报错,容易让人困惑如果想加简单测试,新建 hello_test.go:
package main
import "testing"
func TestHello(t *testing.T) {
want := "Hello, Go!"
got := "Hello, Go!"
if want != got {
t.Errorf("got %q, want %q", got, want)
}
}
然后用 go test 运行 —— 注意文件名必须含 _test.go,函数名必须以 Test 开头,且参数类型为 *testing.T。
真正卡住人的地方往往不是语法,而是模块初始化时机、go run 的作用域判断、以及测试文件命名这些隐性规则。动手建一个空目录,敲三行命令,再写两行 fmt.Println,比读十页文档更能建立直觉。