Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting interface{} to string array

Tags:

go

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

like image 551
user2727195 Avatar asked Mar 11 '17 20:03

user2727195


People also ask

How do I cast an interface to string?

To convert interface to string in Go, use fmt. Sprint function, which gets the default string representation of any value. If you want to format an interface using a non-default format, use fmt. Sprintf with %v verb.

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{} }

How do you implement an interface in Go?

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

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

like image 71
Tim Cooper Avatar answered Oct 21 '22 07:10

Tim Cooper