Casting across types

57 views
Skip to first unread message

Sankar

unread,
Apr 15, 2019, 6:30:48 AM4/15/19
to golang-nuts
I have the following go code:

```
type A map[string]interface{}
type B map[string]interface{}

func f(a A) {
fmt.Println(a)
}

func main() {
var b B
b = make(map[string]interface{})
i := interface{}(b)
f(i.(A))
}
```

This code panics when I try to convert the B instance to type A. What is the right way to do the cast here ?

Sankar P

unread,
Apr 15, 2019, 6:32:30 AM4/15/19
to golang-nuts

திங்., 15 ஏப்., 2019, பிற்பகல் 4:01 அன்று, Sankar <sankar.c...@gmail.com> எழுதியது:
--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/f3jarN-BgC0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--

roger peppe

unread,
Apr 15, 2019, 6:51:17 AM4/15/19
to Sankar P, golang-nuts
The dynamic type conversion needs to specify the exact type that was put into the interface (B in this case).
You can convert it back to A afterwards: https://play.golang.org/p/jBRtR_8RloC

You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.

Sankar P

unread,
Apr 15, 2019, 7:21:08 AM4/15/19
to roger peppe, golang-nuts
Thanks :)

திங்., 15 ஏப்., 2019, பிற்பகல் 4:20 அன்று, roger peppe <rogp...@gmail.com> எழுதியது:

simon place

unread,
Apr 15, 2019, 12:50:26 PM4/15/19
to golang-nuts

may be missing the point, but why go thought an interface{}?


Reply all
Reply to author
Forward
0 new messages