Why is explicit error variable declaration required with database handle?

agolangf · · 195 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>When creating a database handle, where the the variable &#39;db&#39; is declared outside of main, why does this produce a panic: </p> <pre><code>db, err := sql.Open(&#34;mysql&#34;, &#34;user:pass@unix(/path/mysqld.sock)/dbname&#34;) </code></pre> <p>but this doesn&#39;t: </p> <pre><code>var err error db, err = sql.Open(&#34;mysql&#34;, &#34;user:pass@unix(/path/mysqld.sock)/dbname&#34;) </code></pre> <p>the panic is a nil pointer dereference when the first query is run. </p> <hr/>**评论:**<br/><br/>pdffs: <pre><p>I&#39;m fairly sure this exact piece of code is not what&#39;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&#39;t reproduce it, go figure.</p> <p>Thanks for the help though, both of you. </p></pre>tgulacsi: <pre><p>I&#39;m sure you had db var declared global, so with := you created a local db var, and didn&#39;t touch the global, which remained nil.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

195 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传