I’m trying to write a package to work with. Here is sample code:
package redis
import (
"fmt"
"github.com/gomodule/redigo/redis"
"log"
"os"
)
var conn redis.Conn
func init() {
// code to set conn variable
}
func do(command string, args ...interface{}) (interface{}, error) {
init()
return conn.Do(command, args)
}
This code does not compile and compilator says undefined: init
. When I change init()
to Init()
it works, but I don’t want it to be available outside of package.
Wherever I read about this problem, it says about calling unexported function from another package, but here I’m calling it from same one.
Also, Goland IDE marks function call as unresolved reference
and suggests to create it. But when I do (by IDE itself), it still doesn’t see it.
2
Answers
In Go,
init
is reserved for initializing work that needs to be done in a package, eg. adding some implementation to some registry.To solve this problem, you need to use another name.
Take a look at this question to learn more about
init
if you are interested.init() is a special function. From the language spec:
Use
init()
for package level initializations.