Yobert
Yobert

Reputation: 485

How do you typecast a map in Go into a custom type?

I have a custom type defined:

type Thingy map[string]interface{}

and I have a function that is passed an empty interface argument:

func f(arg interface{})

What I'd like to do is be able to typecast arg into a variable of type Thingy. I must be misunderstanding something fundamental about Go because I can't get this to work:

t, ok := arg.(Thingy)

ok always returns false there. Any ideas? Full example here: http://play.golang.org/p/TRZsX4v8-S

Upvotes: 0

Views: 2471

Answers (1)

Dustin
Dustin

Reputation: 90980

  1. That's not a cast, but a type assertion.
  2. You're not passing a Thingy, but a map[string]interface{}

It's important to understand that just because types look similar, that doesn't mean you can use them interchangeably. This is most important when there are method sets. A call to x() on two different types have to be distinguishable even if the underlying types are the same.

Upvotes: 3

Related Questions