Last active
May 8, 2017 20:03
-
-
Save jeffotoni/9036bd9f2f8fef0fb84ffbd85450af7f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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