gpt4 book ai didi

golang 反射(reflect)到 []interface{}

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:26 25 4
gpt4 key购买 nike

我想创建一个迷你框架,它采用一个简单的结构并从中创建一个完整的 crud。我已经开始了,“findOne、更新、创建、删除”正在运行。不是我在创建 findAll 方法时遇到问题。更清楚地说,我不知道如何使用反射将我的 ptr 寻址到结构数组。

这里是 findOne 函数的一个小例子。

type company struct {
Id int
Name string
}

comp.InitModel(newDbConnection(), &comp)

在 InitModel 中,我可以用以下内容填充指向公司的指针:

//m.caller = pointer to the ptr to comp (struct)
callerV := reflect.ValueOf(m.caller)
CallerField := callerV.Elem()
var values []interface{}
for _, e := range m.columns {
values = append(values, CallerField.FieldByName(e.name).Addr().Interface())
}
err := r.Scan(values...)
if err != nil {
return err
}

现在我想创建一个像这样调用的 findAll 方法

var companies []company
comp.InitModel(newDbConnection(), &comp)
comp.FindAll(&companies) //in this is the db query and scan
fmt.Println(companies) //here should be the result

但我在使用 [] 接口(interface)工作时遇到问题。

func (m *Model) FindAll(test []interface{}, c *Condition) error {

//get the sql statement from the struct
stmt := PrepairStmt(m, c)

rows, err := m.db.Query(stmt.selectParse(), c.arguments...)
if err != nil {
return err
}
defer rows.Close()

callerV := reflect.ValueOf(m.caller)
CallerField := callerV.Elem()
for rows.Next() {

var values []interface{}
for _, e := range m.columns {
values = append(values, CallerField.FieldByName(e.name).Addr().Interface())
}

err = rows.Scan(values...)
if err != nil {
return err
}

valuePtr := reflect.New(reflect.TypeOf(test).Elem())
test = reflect.Append(test,reflect.ValueOf(values))
}

return nil
}

那是我最近的尝试。也许有人可以帮助我。我真的很感激

最佳答案

使用 interface{} 而不是 []interface{} 作为参数类型:

func (m *Model) FindAll(result interface{}, c *Condition) error {
stmt := PrepairStmt(m, c)
rows, err := m.db.Query(stmt.selectParse(), c.arguments...)
if err != nil {
return err
}
defer rows.Close()

// resultv is the result slice
resultv := reflect.ValueOf(result).Elem()

// rowt is the struct type
rowt := resultv.Type().Elem()

// allocate a value for the row
rowv := reflect.New(rowt).Elem()

// collect values for scan
var values []interface{}
for _, e := range m.columns {
values = append(values, rowv.FieldByName(e.name).Addr().Interface())
}

for rows.Next() {

err = rows.Scan(values...)
if err != nil {
return err
}

// Append struct to result slice. Because the struct
// is copied in append, we can reuse the struct in
// this loop.
resultv.Set(reflect.Append(resultv, rowv))
}
return nil
}

像这样使用它:

var companies []company
comp.InitModel(newDbConnection(), &comp)
comp.FindAll(&companies) //in this is the db query and scan

关于golang 反射(reflect)到 []interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49264525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com