20

I'm trying to get the data which is stored in interface[] back to string array. Encountering an unexpected error.

type Foo struct { Data interface{} } func (foo Foo) GetData() interface{} { return foo.Data } func (foo *Foo) SetData(data interface{}) { foo.Data = data } func main() { f := &Foo{} f.SetData( []string{"a", "b", "c"} ) var data []string = ([]string) f.GetData() fmt.Println(data) } 

Error: main.go:23: syntax error: unexpected f at end of statement

Go Playground

1 Answer 1

29

What you are trying to perform is a conversion. There are specific rules for type conversions, all of which can be seen in the previous link. In short, you cannot convert an interface{} value to a []string.

What you must do instead is a type assertion, which is a mechanism that allows you to (attempt to) "convert" an interface type to another type:

var data []string = f.GetData().([]string) 

https://play.golang.org/p/FRhJGPgD2z

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for clarification, I've a question, why people or down voting, do they expect I should know this before putting up a question or what?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.