1

I have a struct

type mapKey string

var key1 mapKey = "someKey"
var key2 mapKey = "anotherKey"

type SampleMap map[mapKey]string

Incoming http call has to be map[string]string

which I need to typecast to SampleMap in the business logic

The normal casting : Sample(request) gives an error, cannot convert type map[string]string to SampleMap. Since these both have the same internal type, why is this error occuring and what is the work around?

I really don't want to write a function to map each string to mapKey and then construct SampleMap.

2
  • May I ask the reason to replace string with mapKey? Is there a specific point in case? Commented Oct 21, 2017 at 12:39
  • @AlessandroSantini - SampleMap is owned by a sdk I am using, and there are some operations on the SampleMap exposed by the sdk. Hence, I need an object of type SampleMap. Since internal SampleMap also uses map[string]string, accroding to golang doc I should be able to typecase it simply. But that doesn't work, is there a way to make that work? Commented Oct 22, 2017 at 8:23

1 Answer 1

3

There is no shortcut to coerce maps or arrays from one type to another, as there is for individual types (e.g. mapKey("str") ).

Setting the keys isn't hard though, you can just have a for loop:

params := map[string]string{"someKey": "bar"}

// Copy to type SampleMap
for k, v := range params {
        m[mapKey(k)] = v
}

There isn't much point to having two extra types though (for key and map) unless you enforce limits in some way by using accessors, not allowing direct access. This feels like code translated from another language?

In the absence of other details, I would do this:

// These are the recognised key types for params
const (
  key1 = "someKey"
  key2 = "anotherKey"
)

// Work with this sort of map till you come to convert values:
// When checking keys or using them, use the constants above.
params map[string]string
myVal := params[key1]

What's the rationale for using two types here, to control which keys are used?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.