如何使用 Go 模块修复 Go 构建错误 "can't load package"?

How to fix Go build error "can't load package" with Go modules?

我正在使用带有 this tutorial 的 Go 模块设置一个新项目,然后尝试构建它。

该模块位于 $GOPATH 之外的文件夹中,结构如下:

example.com
├── my-project
├── ├── main
├── ├── ├── main.go
├── ├── go.mod

我在目录 example.com/my-project 中 运行 go mod init example.com/my-project 并创建了上面显示的 go.mod 文件。

main.go有基本内容:

package main

import (
"fmt"
)
func main(){
 fmt.Println("Hello, world!")
}

在目录 example.com/my-project 中尝试 运行 go build 后,我收到以下错误消息:

can't load package: package example.com/my-project: unknown import path "example.com/my-project": cannot find module providing package example.com/my-project.

我也曾尝试 运行 go build 在目录 / 中,在 example.com/my-project 之外,但我得到了类似的失败结果:

can't load package: package .: no Go files in ...

我可能弄错了一些基本的东西,所以感谢你的耐心等待和你能提供的任何帮助。

不需要主目录, 只需将您的 main.go 和 go.mod 移动到示例。com/my-project 它会起作用。

项目根应该如下所示:

.
├── go.mod
└── main.go