r123454321
r123454321

Reputation: 3403

Golang interfaces & casting

I have the following code:

   func returnTheMap() map[string][]string{
        myThing := getSomeValue()
    }

getSomeValue() returns something of type map[string]interface{}

but it is always internally a map[string][]string.

What is the best way to set myThing equal to the same thing as getSomeValue(), but of type map[string][]string?

I can make a new object like so:

newMap := make(map[string][]string)

// cardTypeList is of type map[string]interface {}, must convert to map[string][]string
for k, v := range myThing {
    newMap[k] = v.([]string)
}

but is there any way to do this in-place, or is there any preferred way to do this?

Upvotes: 1

Views: 163

Answers (2)

Nick Rucci
Nick Rucci

Reputation: 1058

Is getSomeValue() your function? If so, I would change the return type to be map[string][]string rather than map[string][]interface.

If that is not the case, I would create some helpers to go through and check to make sure the types are set to your needs. I have an example in the playground

https://play.golang.org/p/9OPgXGXADY

Upvotes: 0

Gary Sham
Gary Sham

Reputation: 503

According to Go FAQ, you cannot change the type of slice directly.

So it seems that your solution is the preferred way.

Upvotes: 6

Related Questions