dragon7713 2013-09-05 06:04
浏览 49
已采纳

前往:如何解压缩结构?

I have a struct:

type mystruct struct {
    Foo string
    Bar int
}

I'd like to create SQL insert statements from the struct which have the following form:

m := mystruct{ "Hello" , 1 }
query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
res,err := db.Exec(query, m.Foo, m.Bar)

Now my question is: how can I make the last line dynamically from the struct (or m) itself? I am able to get the struct names using reflect, but I don't know how to create the []interface{} slice for the db.Exec() call. This is what I have tried: (http://play.golang.org/p/GR1Bb61NFH)

package main

import (
    "fmt"
    "reflect"
)

type mystruct struct {
    Foo string
    Bar int
}

func main() {
    m := mystruct{"Foo", 1}
    fmt.Println(readNames(m))
    x := unpackStruct(m)
    fmt.Printf("%#v
", x)
}

func unpackStruct(a interface{}) []interface{} {

    // "convert" a to m t

    // doesn't work, from 'laws of reflection'
    s := reflect.ValueOf(&t).Elem()
    typeOfT := s.Type()
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        fmt.Printf("%d: %s %s = %v
", i,
            typeOfT.Field(i).Name, f.Type(), f.Interface())
    }

    // this is in principle what I want:
    m := mystruct{"Hello", 2}
    var ret []interface{}
    ret = make([]interface{}, s.NumField())
    ret[0] = m.Foo
    ret[1] = m.Bar
    return ret
}

// works fine:
func readNames(a interface{}) []string {
    s := reflect.TypeOf(a)
    lenStruct := s.NumField()
    ret := make([]string, lenStruct)

    for i := 0; i < lenStruct; i++ {
        ret[i] = s.Field(i).Name
    }
    return ret
}
  • 写回答

2条回答 默认 最新

  • douji5523 2013-09-06 02:55
    关注

    If getting the values of the fields is your issue, this code snippet should help:

    s := reflect.ValueOf(a)
    ret := make([]interface{}, s.NumField())
    for i := 0; i < s.NumField(); i++ {
        ret[i] = s.Field(i).Interface()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。