问题描述
我正在尝试理解 Go 模块并创建一个简单的 hello world 程序。 Go 版本:1.16.2
/project1
/project1/main.go
/project1/helpers/helpers.go
helpers.go
将包含一些实用方法,例如:
package ???
import "fmt"
func DoSomething() {
fmt.Println("Doing something in helpers.go")
}
main.go
将使用 helpers.go
中的方法,如下所示:
package main
import "??"
func main() {
helpers.DoSomething()
}
VSCode 不允许我这样做并且在 helpers
上有一个红色下划线。
我在这里错过了什么?我怎样才能做到这一点?
所以我在 go mod init helpers
文件夹中运行 /helpers
并得出了这个:
/project1/helpers/helpers.go
/project1/helpers/go.mod
go.mod
module helpers
go 1.16
我的 main.go
现在看起来像这样:
package main
import (
"fmt"
"helpers"
)
func main() {
fmt.Println("blah")
helpers.DoHelperMethod()
}
解决方法
您的项目应该只有一个 go.mod
文件并且它应该位于项目的根目录中。您可以 cd
进入项目目录并执行 go mod init <module_name>
其中 <module_name>
在您的情况下可以是 project1
。
例如,一旦您初始化了模块,您的项目应该如下所示:
/project1/helpers/helpers.go
/project1/main.go
/project1/go.mod
go.mod
module project1
go 1.16
main.go
package main
import "project1/helpers"
func main() { helpers.DoHelperMethod() }
helpers/helpers.go
package helpers
func DoHelperMethod() {
// ...
}