Reputation: 7330
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
Upvotes: 20
Views: 26278
Reputation:
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
Upvotes: 29