将map [string] string转换为map [someStruct] string [英] Converting map[string]string to map[someStruct]string

查看:369
本文介绍了将map [string] string转换为map [someStruct] string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

type mapKey string

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

type SampleMap map[mapKey]string

传入的http调用必须是map [string] string

Incoming http call has to be map[string]string

我需要在业务逻辑中将其转换为
SampleMap

which I need to typecast to SampleMap in the business logic

常规转换:Sample(request)给出错误,无法将map [string] string类型转换为SampleMap。
既然它们都具有相同的内部类型,为什么会发生此错误,以及解决方法是什么?

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?

我真的不想编写函数将每个字符串映射到mapKey,然后构造SampleMap。

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

推荐答案

没有将地图或数组从一种类型强制转换为另一种类型的捷径,因为对于单个类型(例如mapKey( str))。

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

虽然设置键并不难,但您可以使用for循环:

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?

这篇关于将map [string] string转换为map [someStruct] string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆