延迟中的“延迟"-会有什么更好的选择? [英] `defer` in the loop - what will be better?

查看:61
本文介绍了延迟中的“延迟"-会有什么更好的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在循环中对数据库进行SQL查询:

I need to make SQL queries to database in the loop:

for rows.Next() {

   fields, err := db.Query(.....)
   if err != nil {
      // ...
   }
   defer fields.Close()

   // do something with `fields`

}

有什么更好的方法:将所有内容保留不变或在循环后移动defer:

What will be better: leave all as is or move defer after loop:

for rows.Next() {

   fields, err := db.Query(.....)
   if err != nil {
      // ...
   }

   // do something with `fields`
}

defer fields.Close()

还有别的吗?

推荐答案

defer的全部要点是直到函数返回才执行,因此将其放置在所需资源后的适当位置关闭是打开的.但是,由于要在循环内创建资源,因此根本不要使用defer-否则,在函数退出之前,您不会关闭在循环内创建的任何资源,因此它们会堆积直到然后.相反,您应该在每次循环迭代结束时关闭它们, defer:

The whole point of defer is that it does not execute until the function returns, so the appropriate place to put it would be immediately after the resource you want to close is opened. However, since you're creating the resource inside the loop, you should not use defer at all - otherwise, you're not going to close any of the resources created inside the loop until the function exits, so they'll pile up until then. Instead, you should close them at the end of each loop iteration, without defer:

for rows.Next() {

   fields, err := db.Query(.....)
   if err != nil {
      // ...
   }

   // do something with `fields`

   fields.Close()
}

这篇关于延迟中的“延迟"-会有什么更好的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆