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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装