Converting []interface{} to []string in Golang
When working with the github.com/fatih/structs package, you may encounter situations where you need to convert []interface{} values obtained from the toValues() function to []string for use with the csv package. However, this conversion cannot be performed directly as these types differ in their memory layout.
To address this issue, you must define how values of various types should be represented as strings. A straightforward approach is to iterate through the values and use fmt.Sprint() to obtain string representations.
Here's a code example demonstrating this:
t := []interface{}{ "zero", 1, 2.0, 3.14, []int{4, 5}, struct{ X, Y int }{6, 7}, } s := make([]string, len(t)) for i, v := range t { s[i] = fmt.Sprint(v) }
This will produce the following output:
[zero 1 2 3.14 [4 5] {6 7}] ["zero" "1" "2" "3.14" "[4 5]" "{6 7}"]
By employing this technique, you can readily convert []interface{} containing values of different types into []string, allowing you to effectively utilize the csv package for further processing.
The above is the detailed content of How to Convert a []interface{} to a []string in Go?. For more information, please follow other related articles on the PHP Chinese website!