英文:
Go custom package import error
问题
我正在尝试编写一个程序,其中的结构如下:
Go/src/
-github.com
-myname
-hello
main.go
-vector
vector.go
当我在main.go
文件中使用如下命令导入包时:
import(
"vector"
)
我收到以下错误信息:
Can't find package "vector" in any of:
C:\Go\src\vendor\vector (vendor tree)
C:\Go\src\vertex (from $GOROOT)
C:\Go\src\github.com\myname\src\vertex (from $GOPATH)
为什么最后一行会添加src
?它不应该将src
替换为hello
文件夹吗?因为我是从那里运行文件的。另外,如果我从完整的文件结构中导入它,例如github.com/myname/hello/vertex
,它就可以运行,这对我来说很奇怪。
我使用go run hello.go
来简化与程序的交互。
英文:
I am trying to write a program where I have a structure like:
Go/src/
-github.com
-myname
-hello
main.go
-vector
vector.go
When I import the package in my code inside of the main.go
file using a command like:
import(
"vector"
)
I get the error message:
Can't find package "vector" in any of:
C:\Go\src\vendor\vector (vendor tree)
C:\Go\src\vertex (from $GOROOT)
C:\Go\src\github.com\myname\src\vertex (from $GOPATH)
Why is it adding src
on that last line? Shouldn't it replace the src with the hello folder since that is where I'm running the file from? Also, it runs if I import it from the full file structure like github.com/myname/hello/vertex
which seems strange to me.
I am executing using go run hello.go
to simplify my interaction with the program.
答案1
得分: 3
你的Go代码(与Go的stdlib相对)应该放在$GOPATH/src
下(编辑:不是$GOROOT
,我最初说错了!),而且通常使用完整的导入路径是标准的,对于你的情况,导入路径应该以github.com/
开头(即使你找到了避免这样做的方法)。
关于如何编写Go代码,Go团队在如何编写Go代码中有更多的内容,这里还有其他回答描述了项目布局和设置工作区的第一步。
英文:
Your Go code (as opposed to Go's stdlib) is meant to be under $GOPATH/src
(edit: not $GOROOT
, as I initially said!), and it's standard to always use the full import path, in your case starting with github.com/
(even if you figured out a way to avoid having to).
There is more in How to Write Go Code by the Go team, and other answers here describing project layout and the first steps to setting a workspace up.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论