我需要帮助理解Golang的包和模块系统的混淆之处。

huangapple go评论92阅读模式
英文:

Need help to understand the confusion that is Golangs package and module system

问题

老实说,Golang的包和模块系统似乎是我遇到过的最不必要复杂的东西。我不知道是我理解有问题,还是关于这个主题缺乏信息,或者只是Golang本身。

我创建了一个Go项目,但我还不想立即发布或上传到GitHub。它不在我设置的GOPATH之内,因为据我所了解,引入模块后,你可以在GOPATH之外编写项目代码。
项目的布局如下:

──── MyProject
     ├─── project
     │    ├─── pkg1
     │    │    └─── foo.go
     │    ├─── pkg2
     │    │    └─── bar.go
     │    └─── go.mod
     └─── test
          └─── test.go

test.go中,我希望能够像这样做:import "project/pkg1",但我不知道如何使其工作。即使我将test.go移动到项目内,并输入import "/pkg1",我也会得到一个“无法导入绝对路径”的错误。

我真的不想每次都把所有的Go项目代码都编写在%GOPATH%/src中,这样做似乎很愚蠢。

再次说明,这可能只是我理解有问题。如果有任何帮助,无论是教程链接还是网站,我都会非常感激。谢谢。

英文:

Honestly, Golang's package and module system seems to be the most needlessly complex thing I've ever had to deal with. I don't know if it's just me not understanding, a lack of information on this subject, or just Golang in general.

I've created a Go project that I don't want to publish just yet or upload to GitHub yet. It's not inside the GOPATH that I set up because from what I understand with the introduction of modules you can code your projects outside the GOPATH.
The project layout is like this

──── MyProject
     ├─── project
     │    ├─── pkg1
     │    │    └─── foo.go
     │    ├─── pkg2
     │    │    └─── bar.go
     │    └─── go.mod
     └─── test
          └─── test.go

In test.go I'd hope that I could do something like import "project/pkg1" but I can't understand how to get it to work. Even if I move test.go inside the project and I type import "/pkg1" I get a Cannot import absolute path error.

I really don't want to have to code all my go projects inside the %GOPATH%/src all the time, it seems silly to have to do that.

Again this is probably just me not understanding. Any help on this, whether it be a link to a tutorial or website, would be appreciated. Thanks.

答案1

得分: 1

如果你是刚接触Go语言的话,我建议你使用go.mod和扁平的项目结构。将你的测试代码与实际代码放在一起。任何以_test.go结尾的文件都不会被包含在内。

foo.go
foo_test.go
bar.go
bar_test.go

如果这是一个库,可以将包名设置为任何你想要的名称。

如果这是一个可执行应用程序,将main设置为根包名。

英文:

If you are new with go I recommend using go.mod and a flat project structure. Keep your tests with actual code. Anything suffixed with _test.go will not be included.

go.mod
foo.go
foo_test.go
bar.go
bar_test.go

If this is a library put package name whatever you want.

If this is an executable application set main as root package name.

huangapple
  • 本文由 发表于 2021年6月13日 04:46:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/67952872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定