4

I want to access a private function of a package called "pastry". But it generates error as: invalid reference to unexported identifier

Specify the way by which private functions of golang are accessible in main.

3
  • 6
    You can't. That's the way the language works. Commented Mar 15, 2016 at 11:29
  • 7
    The whole idea of "private" is to be non-accessible. Commented Mar 15, 2016 at 11:35
  • 1
    Actually it is possible, see my answer. Commented Mar 11, 2020 at 18:30

4 Answers 4

16

You can use go:linkname to map functions from same/different package to some function in yours. For example like:

package main

import (
    "fmt"

    _ "net"
    _ "unsafe"
)

//go:linkname lookupStaticHost net.lookupStaticHost
func lookupStaticHost(host string) []string

func main() {
    fmt.Println(lookupStaticHost("localhost"))
}

will produce [127.0.0.1 ::1] when executed on my machine.

Sign up to request clarification or add additional context in comments.

2 Comments

what about a struct function?
Warning: unexported variables like int or bool are often inlined. go:linkname will be of no help in changing those at run time.
8

Private functions are, by definition, not accessible outside the package in which they are declared.

If you need that function outside that package, you must make it public (change the function name, turning the first letter in upper case).

Eg: if you have func doSomething() rename it to func DoSomething() and use it outside the package with <package name>.DoDomething()

Comments

7

You can also add public proxy-function.

For example:

You have package-private function

func foo() int {
    return 42
}

You can create public function in the same package, which will call the package-private function and return it's result

func Bar() int {
    return foo()
}

Comments

3

in the package (let's say mypackage) where you have pastry function add:

var Pastry = pastry

in main package:

mypackage.Pastry()

1 Comment

You are assuming, that he approves altering the source of the package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.