Skip to content

Instantly share code, notes, and snippets.

@jeffotoni
Last active May 8, 2017 20:03
Show Gist options
  • Select an option

  • Save jeffotoni/9036bd9f2f8fef0fb84ffbd85450af7f to your computer and use it in GitHub Desktop.

Select an option

Save jeffotoni/9036bd9f2f8fef0fb84ffbd85450af7f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
"strconv"
)
type MyStruct struct {
Name string
Age uint
Cpf string
}
func main() {
data_MyStruct := MyStruct{
Name: "Jeff",
Age: 28,
Cpf: "049.393.393-78",
}
stringcsv := structToCsv(&data_MyStruct)
fmt.Println(stringcsv)
}
func structToCsv(i interface{}) (csv string) {
var string_csv string
iVal := reflect.ValueOf(i).Elem()
for i := 0; i < iVal.NumField(); i++ {
f := iVal.Field(i)
var v string
switch f.Interface().(type) {
case int, int8, int16, int32, int64:
v = strconv.FormatInt(f.Int(), 10)
case uint, uint8, uint16, uint32, uint64:
v = strconv.FormatUint(f.Uint(), 10)
case float32:
v = strconv.FormatFloat(f.Float(), 'f', 4, 32)
case float64:
v = strconv.FormatFloat(f.Float(), 'f', 4, 64)
case []byte:
v = string(f.Bytes())
case string:
v = f.String()
}
string_csv = string_csv + v + ";"
}
return string_csv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment