自定义包导入错误

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

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.

huangapple
  • 本文由 发表于 2016年4月6日 01:55:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/36433615.html
匿名

发表评论

匿名网友

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

确定