user2727195
user2727195

Reputation: 7330

casting interface{} to string array

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

Upvotes: 20

Views: 26278

Answers (1)

user142162
user142162

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

Related Questions