错误“无法加载包:包my_prog:找到包my_prog和main”

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

Error "can't load package: package my_prog: found packages my_prog and main"

问题

在我的GOPATH中,我有类似这样的东西:

/bin/
/pkg/
/src/
/src/my_prog/
/src/my_prog/main.go
/src/my_prog/d_interface.go
/src/my_prog/d_struct_that_implements_the_interface.go

main.go中,我有package main,在d_interface.god_struct_that_implements_the_interface.go中,我有package my_prog

当我尝试go build my_prog时,我得到以下错误:

无法加载包:包my_prog找到了包my_prog(d_interface.go)和main(main.go)在C:\dev\Code\Go\src\my_prog中

这是否意味着属于package main的任何文件都应该放在自己的文件夹中?如果是这样,这是什么原因?

英文:

In my GOPATH I have something like this:

/bin/
/pkg/
/src/
/src/my_prog/
/src/my_prog/main.go
/src/my_prog/d_interface.go
/src/my_prog/d_struct_that_implements_the_interface.go

In main.go I have package main, in d_interface.go and d_struct_that_implements_the_interface.go I have package my_prog.

When I try to go build my_prog I get the following error:

can't load package: package my_prog: found packages my_prog (d_interface.go) and main (main.go) in C:\dev\Code\Go\src\my_prog

Does this mean that any file that belongs to package main should go in its own folder? If so, what is the reason for this?

答案1

得分: 81

是的,每个包都必须在自己的目录中定义。

源代码结构在如何编写Go代码中定义。

一个包是一个组件,你可以在多个程序中使用它,可以发布、导入、从URL获取等等。因此,它有自己的目录就像一个程序有一个目录一样是有意义的。

英文:

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

答案2

得分: 21

此外,如果你只是想将main.go文件拆分成多个文件,那么只需将其他文件命名为"package main",只要在这些文件中只定义一个main函数,就可以顺利进行。

英文:

Also, if all you are trying to do is break up the main.go file into multiple files, then just name the other files "package main" as long as you only define the main function in one of those files, you are good to go.

答案3

得分: 2

确保你的包已经安装在你的$GOPATH目录中,或者已经在你的工作空间/包中。

例如:如果你的$GOPATH = "c:\go",确保包在C:\Go\src\pkgName中。

英文:

Make sure that your package is installed in your $GOPATH directory or already inside your workspace/package.

For example: if your $GOPATH = "c:\go", make sure that the package inside C:\Go\src\pkgName

huangapple
  • 本文由 发表于 2013年1月20日 00:21:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/14416275.html
匿名

发表评论

匿名网友

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

确定