go 结构体 转string,Golang:类型转换-将map [string] string转换为map [someStruct] string

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.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值