英文:
How do I make go find my package?
问题
在哪里放置我的包,以便可以被另一个包导入?
$ tree
.
├── main.go
└── src
└── test.go
1个目录,2个文件
$ cat src/test.go
package test
$ cat main.go
package main
import "test"
$ go build main.go
main.go:3:8: import "test": 找不到包
英文:
Where should I put my package so that it can be imported by another package?
$ tree
.
├── main.go
└── src
└── test.go
1 directory, 2 files
$ cat src/test.go
package test
$ cat main.go
package main
import "test"
$ go build main.go
main.go:3:8: import "test": cannot find package
答案1
得分: 11
设置你的GOPATH。将你的包foo的源代码放在GOPATH/src/optional-whatever/foo/*.go中,并在代码中使用它:
import "optional-whatever/foo"
你不需要显式安装foo,go工具是一个构建工具,它会在必要时自动为你安装。
英文:
Set your GOPATH. Put your package foo source(s) in GOPATH/src/optional-whatever/foo/*.go and use it in code as
import "optional-whatever/foo"
You don't need to explicitly install foo, the go tool is a build tool, it will do that automagically for you whenever necessary.
答案2
得分: 8
有几件事情需要完成。首先,您必须先安装“test”包:
$ export GOPATH=$(pwd) # 假设使用的是 Bourne shell(而不是 csh)
$ mkdir src/test
$ mv src/test.go src/test/test.go
$ mkdir pkg # go install 将把包放在这里
$ go install test # 构建包并将其放在 $GOPATH/pkg 中
$ go build main.go
请注意,创建 pkg 目录并不是必需的,因为 go install
会为您创建它。
一旦您安装了 test 包(顺便说一句,这个命名通常不好),go build main.go
现在应该会给出不同的错误(例如,“imported and not used”)。
英文:
There are a few things that need to happen. You must install the "test" package first:
$ export GOPATH=$(pwd) # Assumes a bourne shell (not csh)
$ mkdir src/test
$ mv src/test.go src/test/test.go
$ mkdir pkg # go install will put packages here
$ go install test # build the package and put it in $GOPATH/pkg
$ go build main.go
Note that it is not necessary to create pkg, as go install
will do that for you.
Once you've installed the test package (generally a bad name, BTW) go build main.go
should now give different errors (eg, "imported and not used")
答案3
得分: -3
也许,你可以将test.go文件放在与main.go相同的目录中,并且在test.go中使用类似以下的代码:
import "./test"
英文:
maybe, you can put the test.go file in the same directory with the main.go, and
in test.go, it uses something like this:
import "./test"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论