dtg78700 2018-10-23 04:48
浏览 10
已采纳

将本地结果分配给外部范围

I have this block of code. The problem is in the func, I am trying to assign to the db var in outer scope, but it ends up being declared as a local variable.

var db *sqlx.DB

func GetDatabaseConnection() *sqlx.DB {

    if db == nil {

        db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
        if err != nil {
            log.Fatalln(err)
        }

    }

    return db
}

my question is, regarding this line:

db, err := sqlx.Connect(...)

how can I assign db to the outer scope, and not declare it as a local varible?

  • 写回答

1条回答 默认 最新

  • duanmen8491 2018-10-23 04:54
    关注
    var db *sqlx.DB
    
    func GetDatabaseConnection() *sqlx.DB {
    
        if db == nil {
            var err error # ADD THIS LINE, AND DO = INSTEAD OF := ON NEXT LINE
            db, err = sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
            if err != nil {
                log.Fatalln(err)
            }
    
        }
    
        return db
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥15 mssql2000游标循环次数对不上
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能
  • ¥15 关于#单片机#的问题:K210 例程里面提示我iomem.h: No such file or directory
  • ¥15 LSPI算法的大问题
  • ¥15 java导出word 动态填充数据
  • ¥20 扑克的算牌公式及软件制作
  • ¥20 如何通过云图中RPG去计算云图上不同位置的值?