2019-06-07 14:00 阅读 204

在Golang中将named-type map [string] string转换成普通的一个

I have a map of type set, which is actually a map[string]string. However, passing it to a function which accepts a map[string]string fails, because Go does not recognize set as one.

However, I fail to convince the compiler it is one. Is there any way to resolve this, without looping and copying?

package main

import (

type name string
type field string

type set map[name]field      // map[string]string after all
type plain map[string]string // also map[string]string

func main() {
    var typed = set{"hi": "ho"} // map[string]string?

    back := plain(typed)  // cannot convert typed (type set) to type plain
    back := typed.(plain) // invalid type assertion: typed.(plain) (non-interface type set on left)


func echo(in map[string]string) {
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanli6618 duanli6618 2019-06-07 15:14

    You could do this using the unsafe package.

    Note: I don't think this would necessarily be a good idea, and probably the right way would be to just iterate and copy, but since it does answer the question asked...

    var typed = set{"hi": "ho"} // map[string]string?
    p := unsafe.Pointer(&typed)
    var back plain
    back = *(*plain)(p)

    Playground: https://play.golang.org/p/yienSuJSnQU

    点赞 评论 复制链接分享