I have piece of code in which I get error when I use :=
but when I use =
it compiles properly. What I learned is that :=
only requires only atleast one variable to be defined, others need not be defined, but considering this code is it a bug in Go?
Uncompilable code:
Error: services/db_service.go:16: Session declared and not used
package services
import (
"gopkg.in/mgo.v2"
"log"
)
const DB = "mmdb_dev"
var Session *mgo.Session
func InitMongo() bool {
url := "mongodb://localhost"
log.Println("Establishing MongoDB connection...")
//var err error
Session, err := mgo.Dial(url)
if err != nil {
log.Fatal("Cannot connect to MongoDB!")
return true
} else {
return false
}
}
func GetNewSession() mgo.Session {
return *Session.Copy()
}
Compiled code
package services
import (
"gopkg.in/mgo.v2"
"log"
)
const DB = "mmdb_dev"
var Session *mgo.Session
func InitMongo() bool {
url := "mongodb://localhost"
log.Println("Establishing MongoDB connection...")
var err error
Session, err = mgo.Dial(url)
if err != nil {
log.Fatal("Cannot connect to MongoDB!")
return true
} else {
return false
}
}
func GetNewSession() mgo.Session {
return *Session.Copy()
}
The change is
Session, err := mgo.Dial(url)
to
var err error
Session, err = mgo.Dial(url)