Go: Access private function

A package is the smallest unit of private encap­sulation in Go.

  • All identifiers defined within a package are visible throughout that package.
  • When importing a package you can access only its exported identifiers, which are public.
  • An identifier is exported if it begins with a capital letter, in other words, an identifier with a lower case letter if private.

However, sometimes, we have to use some private function test a specific function more easily. There are several methods you can do that.

Method 1: If you have a package-private function

func foo() int {
    return 42

You can create a public function in the same package, which will call the package-private function and return its result

func Bar() int {
    return foo()

Then, you can import that public function to indirectly use that private function.

Method 2: you can use go:linkname https://golang.org/cmd/compile/

For example, you have a package-private function in package A

func foo() int {
    return 42

if you want to use a private function of package A in package B,

import _ "unsafe"
//go:linkname localname [importpath.name]
func foo() int

Then, you can directly use that private function for your purpose.

Question mark: how to access private parameters in other packages?

Interesting article. As an extended topic, if a type is package-private, should all its methods all be private?