dtypj3308 2016-03-16 09:00
浏览 260

无法在go lang中分配* gorm.DB

I'm trying to return a instance from the gorm.Open() return it i'm getting following error

controllers/db.go:34: cannot assign *gorm.DB to dc.DB (type gorm.DB) in multiple assignment

This is the db.go controller

    package controllers

import (

  //"fmt"

  _ "github.com/go-sql-driver/mysql"
  //v "github.com/spf13/viper"
  "github.com/jinzhu/gorm"

)

type DBController struct {
    DB gorm.DB
}

func (dc *DBController) InitDB() {
    var err error


    dc.DB, err = gorm.Open("mysql","root:12345@tcp(localhost:3306)/api")
    if err != nil {
        log.Fatalf("Error when connect database, the error is '%v'", err)
    }
    dc.DB.LogMode(true)
}

func (dc *DBController) GetDB() gorm.DB {
  return dc.DB
}

What is reason for this error and how can i fix this?

  • 写回答

1条回答 默认 最新

  • duanjian3338 2016-03-16 09:02
    关注

    You need and most probably you want to have a pointer in the structure of controller. Passing structure with a pointer to the database object (gorm.DB) will prevent Go from making a copy of this object (gorm.DB).

    Do the following:

    type DBController struct {
        DB *gorm.DB
    }
    

    Now it should work fine.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100