英文:
Internal packages in Go
问题
如何在Go中导入内部包?
import (
"runtime/internal/atomic"
"runtime/internal/sys"
)
像这样导入时,会出现错误:
imports runtime/internal/atomic: use of internal package not allowed
在主包中使用内部函数?
英文:
How to import internals packages in Go ?
import (
"runtime/internal/atomic"
"runtime/internal/sys"
)
Like this without get a error:
> imports runtime/internal/atomic: use of internal package not allowed
And use internal funcs in a main package ?
答案1
得分: 21
背景
Go语言鼓励将程序结构化为一组使用导出API进行交互的包。然而,所有的包都可以被导入。这在实现库或命令时会产生一种紧张感:它可能变得足够大,以至于需要将其结构化为多个包,但拆分它会将这些额外包中使用的API公开给全世界。能够创建具有受限可见性的包将消除这种紧张感。
提议的规则(适用于Go 1.4)
如果导入路径中包含"internal"元素,并且导入代码位于"internal"目录的父目录树之外,则禁止导入。
简短回答
你不能(至少不容易),也不应该这样做。
英文:
Background
> Go encourages structuring a program as a collection of packages interacting using exported APIs. However, all packages can be imported. This creates a tension when implementing a library or command: it may grow large enough to structure as multiple packages, but splitting it would export the API used in those additional packages to the world. Being able to create packages with restricted visibility would eliminate this tension.
A rule proposed to Go 1.4
An import of a path containing the element “internal” is disallowed if the importing code is outside the tree rooted at the parent of the “internal” directory.
Short answer
You can't (at least easily) and you shouldn't.
答案2
得分: 4
我将向您展示我如何使用内部的nettest包:
// 我使用dep ensure
将nettest复制到了vendor中。然后:
mkdir vendor-local
cp -r vendor/golang.org/x/net/internal/nettest ./vendor-local/nettest
vim ./vendor-local/nettest/stack.go 并删除导入注释 // import "foo" 1
// 在您的go文件中使用完整的导入路径:
import "github.com/foo-user/bar-project/vendor-local/nettest"
您可以使用grep -r "// import" ./vendor-local/nettest
在您的内部包中找到所有的导入注释。
为什么我不能将nettest复制到./vendor并使用较短的导入路径
您可以这样做,但是像dep ensure
这样不支持本地包的工具会清除您的复制品。
英文:
I will show you how I use internal nettest package:
// I copied nettest to vendor with `dep ensure` I think. Then:
mkdir vendor-local
cp -r vendor/golang.org/x/net/internal/nettest ./vendor-local/nettest
vim ./vendor-local/nettest/stack.go and remove import comment // import "foo" [1]
// Use full import in your go file:
import "github.com/foo-user/bar-project/vendor-local/nettest"
You may find all import comments in your internal package with grep -r "// import" ./vendor-local/nettest
Why can't I copy nettest to ./vendor and use shorter import
You can, but utils like dep ensure
that don't support local packages will purge your copy.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论