Internal packages in Go

2019-05-05 20:04发布

问题:

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:

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:

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"

[1]: https://github.com/golang/net/blob/a8b9294777976932365dabb6640cf1468d95c70f/internal/nettest/stack.go#L6

Docs about import comments

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.