Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert []interface to []string in Golang

Tags:

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?

like image 813
Rogier Lommers Avatar asked May 17 '17 14:05

Rogier Lommers


People also ask

What is interface {} Golang?

interface{} is the Go empty interface, a key concept. Every type implements it by definition. An interface is a type, so you can define for example: type Dog struct { Age interface{} }

What is type assertion in Golang?

Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.

How do you implement an interface in Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.


1 Answers

You can't simply convert []interface{} to []string even if all the values are of concrete type string, because those 2 types have different memory layout / representation. For details see Cannot convert []string to []interface {}.

You have to define how you want values of different types to be represented by string values.

The easiest and sensible way would be to iterate over the values, and use fmt.Sprint() to obtain a string representation of each, e.g.:

t := []interface{}{     "zero",     1, 2.0, 3.14,     []int{4, 5},     struct{ X, Y int }{6, 7}, } fmt.Println(t)  s := make([]string, len(t)) for i, v := range t {     s[i] = fmt.Sprint(v) } fmt.Println(s) fmt.Printf("%q\n", s) 

Output (try it on the Go Playground):

[zero 1 2 3.14 [4 5] {6 7}] [zero 1 2 3.14 [4 5] {6 7}] ["zero" "1" "2" "3.14" "[4 5]" "{6 7}"] 
like image 50
icza Avatar answered Sep 23 '22 17:09

icza