Reputation: 115
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.
Upvotes: 4
Views: 12570
Reputation: 7480
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.
Upvotes: 16
Reputation: 31
in the package (let's say mypackage) where you have pastry function add:
var Pastry = pastry
in main package:
mypackage.Pastry()
Upvotes: 3
Reputation: 826
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()
}
Upvotes: 7
Reputation: 27042
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()
Upvotes: 8