Why is explicit error variable declaration required with database handle?

agolangf · 2018-04-13 17:30:11 · 564 次点击    
这是一个分享于 2018-04-13 17:30:11 的资源,其中的信息可能已经有所发展或是发生改变。

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:

I'm fairly sure this exact piece of code is not what's causing your problem, you may need to provide more context.

earthboundkid:

Sounds like a scope error. Probably DB is both a package variable and a function variable but without context that’s just a guess.

GunsKnivesRadios:

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.

tgulacsi:

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.


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

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