duanping2809 2019-04-03 13:31
浏览 44
已采纳

如何从另一个函数调用dbmap.Insert(interface {})?

I have a bunch of very similar structs (A and B in the example) whose instances I want to handle in some function ( f() in the example) and then insert them into my database. I figured I could handle that with the empty interface somehow, but it seems this is not the solution as I get the error:

i: &{{6 2019-04-03 15:11:37.822100431 +0200 CEST m=+0.001291882} 7} *main.A
2019/04/03 15:11:37 Insert i no table found for type: 
exit status 1

I tried to create some minimal but executable example:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
    gorp "gopkg.in/gorp.v2"
    "log"
    "time"
)

type Meta struct {
    Id        int
    CreatedAt time.Time
}

type A struct {
    Meta
    Value int
}

type B struct {
    Meta
    Value string
}

var dbmap *gorp.DbMap

func f(i interface{}) {
    fmt.Printf("i: %v %T
", i, i)

    err := dbmap.Insert(&i)
    checkErr(err, "Insert i")
}

func main() {
    Init()

    a := A{Meta: Meta{CreatedAt: time.Now()}, Value: 7}
    b := B{Meta: Meta{CreatedAt: time.Now()}, Value: "seven"}

    err := dbmap.Insert(&a)    // works
    checkErr(err, "Insert a")

    err = dbmap.Insert(&b)     // works
    checkErr(err, "Insert b")

    f(&a) // fails
}

func Init() {
    db, err := sql.Open("sqlite3", "/tmp/post_db.bin")
    checkErr(err, "sql.Open failed")
    dbmap = &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
    dbmap.AddTableWithName(A{}, "As").SetKeys(true, "Id")
    dbmap.AddTableWithName(B{}, "Bs").SetKeys(true, "Id")
    err = dbmap.CreateTablesIfNotExists()
    checkErr(err, "Couldn't create tables")
}

func checkErr(err error, msg string) {
    if err != nil {
        log.Fatalln(msg, err)
    }
}

What's the right way to do that? In C++ I'd simply use templates ;)

  • 写回答

1条回答 默认 最新

  • doufu5521 2019-04-04 12:30
    关注

    If you are calling you func like f(&a). You should call inside func f just dbmap.Insert(i), because your value is already a pointer. So your func will look like

    func f(i interface{}) {
        fmt.Printf("i: %v %T
    ", i, i)
    
        err := dbmap.Insert(i)
        checkErr(err, "Insert i")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作