The following code doesn't convert: http://play.golang.org/p/8kWAndjG9Z
My main objective is to make a lots of structs with similar definitions to use a specific function using the power of interfaces. MyTestStruct.Data can be typed anything including int, string, []string, struct etc.
评论:
rco8786:
QThellimist:It looks like you're trying to fake generics.
In general though, you're trying to cast an anonymous struct with the signature
Id int, Data interface
to a named struct with the signatureId int, Data []string
. I'm not sure why you'd expect that to work.
rco8786:This works http://play.golang.org/p/HtD2OKViJ6
This doesn't work http://play.golang.org/p/JZAQjEb8il (I changed the type from []string to interface{})Conversion between struct to struct doesn't work including casting to interface{}. Maybe there is a work around.
barsonme:Because you're casting from interface{} to interface{}.
QThellimist:It works because they're all pointers to type
T
In your other example you have two fundamentally different types:
type foo struct { A int; B []string } bar := foo{ A: 21, B: []string{"Hello, world!"}, }
and
baz := struct { A int B interface{} } { A: 21, B: []string{"Hello, world!"}, }
jerf:True. Is there a work around you can think of?
No. Go is neither covariant nor contravariant. Types are either equal or they aren't.
You have to either take the structs apart and deal with the pieces, or use reflection. Type assertions are only "assertions", not "coercions" of any kind.
