如何使用自定义包 [英] How to use custom packages
问题描述
我正在尝试在Go中创建和使用自定义包.这可能很明显,但是我找不到很多信息.基本上,我在同一个文件夹中有这两个文件:
I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:
mylib.go
package mylib
type SomeType struct {
}
main.go
package main
import (
"mylib"
)
func main() {
}
当我尝试go run main.go
时,出现此错误:
When I try to go run main.go
, I get this error:
main.go:4:2: import "mylib": cannot find package
我尝试先运行go build mylib.go
,但是它似乎没有执行任何操作(未生成文件,未显示错误消息).所以知道我该怎么做吗?
I've tried to run go build mylib.go
first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?
推荐答案
首先,请务必阅读并理解如何编写Go代码" 文档.
First, be sure to read and understand the "How to write Go code" document.
实际答案取决于您的自定义程序包"的性质.
The actual answer depends on the nature of your "custom package".
如果打算用于一般用途,请考虑使用所谓的"Github代码布局" .基本上,您将库设为一个单独的go get
-table项目.
If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate go get
-table project.
如果您的库供内部使用,则可以这样:
If your library is for internal use, you could go like this:
- 将包含库文件的目录放置在项目目录下.
- 在项目的其余部分,请使用相对于包含该项目的工作空间的根目录的路径来引用该库.
演示:
src/
myproject/
mylib/
mylib.go
...
main.go
现在,在顶级main.go
中,您可以import "myproject/mylib"
,它将正常运行.
Now, in the top-level main.go
, you could import "myproject/mylib"
and it would work OK.
这篇关于如何使用自定义包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!