Converting map[string]string to map[someStruct]string

后端 未结 1 1314
清酒与你
清酒与你 2020-12-21 20:37

I have a struct

type mapKey string

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

type SampleMap map[mapKey]string

Incomi

相关标签:
1条回答
  • 2020-12-21 21:10

    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?

    0 讨论(0)
提交回复
热议问题