Search code examples
gotiedot

Why is my tiedot DB pointer nil?


var myDB *db.DB

func init() {
    myDB, err := db.OpenDB("db")
    if err := myDB.Create("Feeds"); err != nil {}
    if err := myDB.Create("Votes"); err != nil {}
}

func idb() {
    for _, name := range myDB.AllCols() {
        fmt.Printf("I have a collection called %s\n", name)
    }    
}

func main() {
    idb()
}

I get the following error:

runtime error: invalid memory address or nil pointer dereference

It is probably because myDB is nil, but why and how can I fix it so I can setup myDB in init?

Note that if I just drop everything in main without using a global variable, it works.


Solution

  • Short variable declarations

    A short variable declaration uses the syntax:

    ShortVarDecl = IdentifierList ":=" ExpressionList .
    

    It is shorthand for a regular variable declaration with initializer expressions but no types:

    "var" IdentifierList = ExpressionList .
    

    myDB is a local init function variable. := is a short variable declaration.

    myDB, err := db.OpenDB("db")
    

    To update package myDB variable, write,

    var err error
    myDB, err = db.OpenDB("db")