本文介绍了Golang:类型转换-将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?

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

07-29 14:13
查看更多