<p>When creating a database handle, where the the variable 'db' is declared outside of main, why does this produce a panic: </p>
<pre><code>db, err := sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
</code></pre>
<p>but this doesn't: </p>
<pre><code>var err error
db, err = sql.Open("mysql", "user:pass@unix(/path/mysqld.sock)/dbname")
</code></pre>
<p>the panic is a nil pointer dereference when the first query is run. </p>
<hr/>**评论:**<br/><br/>pdffs: <pre><p>I'm fairly sure this exact piece of code is not what's causing your problem, you may need to provide more context.</p></pre>earthboundkid: <pre><p>Sounds like a scope error. Probably DB is both a package variable and a function variable but without context that’s just a guess. </p></pre>GunsKnivesRadios: <pre><p>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.</p>
<p>Thanks for the help though, both of you. </p></pre>tgulacsi: <pre><p>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.</p></pre>
