-2

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())
  }
}
snowpeak
  • 797
  • 9
  • 25
  • It is unclear from the question what you want to achieve. Please provide more information on what you want and what you don't – Himanshu Aug 18 '18 at 14:33
  • I want to use this function ```Connect()``` in another package but variable ```db``` causes "declared and not used" error in the package it was initialized in. – snowpeak Aug 18 '18 at 14:36
  • 1
    Your variable `db` cannot possibly be used from another package--or even in the same package, outside of the `Connect()` function... so I'm not really sure what you're asking. – Jonathan Hall Aug 18 '18 at 14:41
  • What is the purpose of using `Connect`, so that you can return the `*sql.DB` session to connect to the database. – Himanshu Aug 18 '18 at 14:41
  • @ShiningGo you should look at the example – Or Yaacov Aug 18 '18 at 14:44

1 Answers1

3

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())
      }
    }
Or Yaacov
  • 3,597
  • 5
  • 25
  • 49
  • I think this is what I was looking for! to make the variable Global. – snowpeak Aug 18 '18 at 14:48
  • 2
    Except you maybe shouldn't use a global var: https://peter.bourgon.org/blog/2017/06/09/theory-of-modern-go.html ;-) – TommyF Aug 18 '18 at 15:24
  • Saying you "should" use global variables is bad, IMO. True, this addresses the specific issue brought up by the OP, but it's usually bad practice. – Jonathan Hall Aug 18 '18 at 16:17
  • maybe that global wasn't in place. so how would you guys manage the db instance? @TommyF I read the article and in there he send a pointer to the db as an argument in the end, but he still had to declare it as a var somewhere, so what is the best practice in your opinion? – Or Yaacov Aug 18 '18 at 16:46