skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. init() is a special function. From the language spec:

    func init() { … }

    Multiple such functions may be defined per package, even within a
    single source file. In the package block, the init identifier can
    be used only to declare init functions, yet the identifier itself
    is not declared. Thus init functions cannot be referred to from
    anywhere in a program.

    Use init() for package level initializations.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search