I saw this post How to avoid annoying error "declared and not used"
but I don't know if this is the right way to handle the error, when I use the variable in other packages.
for example, in case I use Connect()
only in other packages, I don't use variable db
in this package.
func Connect() {
db, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
if err != nil {
panic(err.Error())
}
}
the best way to avoid the "annoying" declared and not used you shouldn't declare a variable that you are not using, if for instance you are not need to use an variable that returns from a function you can use _ to ignore it. like in here:
func Connect() {
_, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
if err != nil {
panic(err.Error())
}
}
But you will need use your DB instance at other parts of your code so you will need to declare your variable with like that:
var DBInstance *sql.db
and then you will be able to access the db pointer from anywhere in the package
so full example will be:
var DBInstance *sql.db
func Connect() {
db, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
if err != nil {
panic(err.Error())
}
}