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
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.
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{} }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With