Convert []interface to []string in Golang

Viewed 27873

I'm using the github.com/fatih/structs package to convert values of all fields of a struct into []interface{} with the toValues() function. See here. This works fine, but eventually I want to write the values to a csv file by using the csv package. The csv.Write() function requires []string as input.

So in short: how can I easily convert the output of toValues() into an array of strings?

2 Answers

Use fmt.Sprintf to convert an interface value to a string. In fact, this technique can be used to get a string representation of any data structure.

Here is the code sample,

var Foo interface{} = "Value"

str := fmt.Sprintf("%v", Foo)
Related