英文:
What does the Go compiler mean by "no such file or directory"?
问题
我正在尝试编译一个由多个模块组成的Go程序,如下所示:
// main.go
package main
import "mst"
// 进行一些涉及最小生成树的有趣操作
// src/mst/kruskal.go
import "disjsets"
// 实现Kruskal算法
// src/disjsets/disjsets.go
// 使用并查集实现
现在,当我在包含main.go
和src
目录的目录中运行go run main.go
或go build
之后,它会打印出:
# disjsets
open src/disjsets/disjsets.go: No such file or directory
我不明白这个问题。ls -l src/disjsets/disjsets.go
确认该文件存在。为什么会发生这种情况?如果要让Go找到它,disjsets.go
文件应该放在哪里?
(Google Go 1.0.2)
英文:
I'm trying to compile a Go program made up of multiple modules, like so:
// main.go
package main
import "mst"
// do something interesting involving minimum spanning trees
// src/mst/kruskal.go
import "disjsets"
// Kruskal's algorithm follows
// src/disjsets/disjsets.go
// implements disjoint sets with union-find
Now, when I run either go run main.go
or go build
after export GOPATH=.
in the directory containing both main.go
and src
, it prints
# disjsets
open src/disjsets/disjsets.go: No such file or directory
I don't get this. The file is there as ls -l src/disjsets/disjsets.go
confirms. How can this happen? Where should the disjsets.go
file live if Go is to find it?
(Google Go 1.0.2)
答案1
得分: 8
我相信你应该阅读或重新阅读如何编写Go代码
简而言之:
将你的GOPATH设置为某个位置并导出它。然后将一些包blah
放入以下目录中:
$GOPATH/src/foo/bar/baz/blah # (1)
或者
$GOPATH/src/blah # (2)
或者
$GOPATH/src/qux/blah # (3) 等等。
将blah
导入其他包中:
import "foo/bar/baz/blah" // (1)
或者
import "blah" // (2)
或者
import "qux/blah" // (3)
该目录中的包将包含包文件。假设你只有一个文件,blah.go
。那么它的位置将是:
$GOPATH/src/foo/bar/baz/blah/blah.go // (1)
$GOPATH/src/blah/blah.go // (2)
$GOPATH/src/qux/blah/blah.go // (3)
如果blah
包的源文件命名为proj.go
,那么位置将是:
$GOPATH/src/foo/bar/baz/blah/proj.go // (1)
$GOPATH/src/blah/proj.go // (2)
$GOPATH/src/qux/blah/proj.go // (3)
但导入路径与前面的情况相同。
英文:
I believe you should read, or re-read How to Write Go code
In short:
Set you GOPATH to somewhere and export it for good. Then put some package blah
into directory
$GOPATH/src/foo/bar/baz/blah # (1)
or
$GOPATH/src/blah # (2)
or
$GOPATH/src/qux/blah # (3) etc.
Import blah
into other packages as
import "foo/bar/baz/blah" // (1)
or
import "blah" // (2)
or
import "qux/blah" // (3)
The package in that directory will contain the package files. Say you have only one, blah.go
. Then its location would be
$GOPATH/src/foo/bar/baz/blah/blah.go // (1)
$GOPATH/src/blah/blah.go // (2)
$GOPATH/src/qux/blah/blah.go // (3)
If the blah package source file is named, say proj.go
instead, then
$GOPATH/src/foo/bar/baz/blah/proj.go // (1)
$GOPATH/src/blah/proj.go // (2)
$GOPATH/src/qux/blah/proj.go // (3)
But the import paths would be the same as in the previous case.
答案2
得分: 3
好的,这似乎解决了问题:
export GOPATH=`pwd`
显然,它需要是一个绝对路径。尽管如此,我仍然觉得错误信息非常令人困惑。
英文:
Ok, this seems to solve it:
export GOPATH=`pwd`
Apparently, it needs to be an absolute path. I still find the error message very confusing, though.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论