Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: How can I "unpack" a struct?

Tags:

reflection

go

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\n", 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\n", 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
}
like image 920
topskip Avatar asked Nov 02 '22 15:11

topskip


1 Answers

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()
}
like image 113
joshlf Avatar answered Dec 10 '22 09:12

joshlf