Last active
August 7, 2021 19:12
-
-
Save pmn/5374494 to your computer and use it in GitHub Desktop.
Convert an interface{} containing a slice of structs to [][]string (used in CSV serialization) [golang reflection example] Runnable example here: http://play.golang.org/p/ZSJRxkpFs9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Convert an interface{} containing a slice of structs into [][]string. | |
func recordize(input interface{}) [][]string { | |
var records [][]string | |
var header []string // The first record in records will contain the names of the fields | |
object := reflect.ValueOf(input) | |
// The first record in the records slice should contain headers / field names | |
if object.Len() > 0 { | |
first := object.Index(0) | |
typ := first.Type() | |
for i := 0; i < first.NumField(); i++ { | |
header = append(header, typ.Field(i).Name) | |
} | |
records = append(records, header) | |
} | |
// Make a slice of objects to iterate through & populate the string slice | |
var items []interface{} | |
for i := 0; i < object.Len(); i++ { | |
items = append(items, object.Index(i).Interface()) | |
} | |
// Populate the rest of the items into <records> | |
for _, v := range items { | |
item := reflect.ValueOf(v) | |
var record []string | |
for i := 0; i < item.NumField(); i++ { | |
itm := item.Field(i).Interface() | |
record = append(record, fmt.Sprintf("%v", itm)) | |
} | |
records = append(records, record) | |
} | |
return records | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if it can help other people like it was for me
// Convert an interface{} containing a slice of structs to []PairKeyValue
// Convert an interface{} containing a struct to PairKeyValue