title: Go: How can I "unpack" a struct?
body: <p>I have a struct:</p>
  
  <pre><code>type mystruct struct {
      Foo string
      Bar int
  }
  </code></pre>
  
  <p>I'd like to create SQL insert statements from the struct which have the following form:</p>
  
  <pre><code>m := mystruct{ "Hello" , 1 }
  query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
  res,err := db.Exec(query, m.Foo, m.Bar)
  </code></pre>
  
  <p>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 <code>reflect</code>, but I don't know how to create the <code>[]interface{}</code> slice for the <code>db.Exec()</code> call. This is what I have tried: (<a href="http://play.golang.org/p/GR1Bb61NFH" rel="noreferrer">http://play.golang.org/p/GR1Bb61NFH</a>)</p>
  
  <pre><code>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(&amp;t).Elem()
      typeOfT := s.Type()
      for i := 0; i &lt; 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 &lt; lenStruct; i++ {
          ret[i] = s.Field(i).Name
      }
      return ret
  }
  </code></pre>