When creating a database handle, where the the variable 'db' is declared outside of main, why does this produce a panic:
db, err := sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
but this doesn't:
var err error
db, err = sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
the panic is a nil pointer dereference when the first query is run.
评论:
pdffs:
earthboundkid:I'm fairly sure this exact piece of code is not what's causing your problem, you may need to provide more context.
GunsKnivesRadios:Sounds like a scope error. Probably DB is both a package variable and a function variable but without context that’s just a guess.
tgulacsi:Or something even dumber. I cut it down to just enough code to make a database handle and run a query and now I can't reproduce it, go figure.
Thanks for the help though, both of you.
I'm sure you had db var declared global, so with := you created a local db var, and didn't touch the global, which remained nil.
