如何让go找到我的包裹?

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

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"

huangapple
  • 本文由 发表于 2012年5月15日 20:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/10600776.html
匿名

发表评论

匿名网友

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

确定