dictionary - 在 Golang 中将命名类型映射[字符串]字符串转换为普通类型

标签 dictionary go types

我有一个set类型的 map ,它实际上是一个map[string]string。但是,将其传递给接受 map[string]string 的函数会失败,因为 Go 无法将 set 识别为 1。

但是,我无法说服编译器它是一个。有没有办法解决这个问题,而不需要循环和复制?

package main

import (
    "fmt"
)

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)

    echo(back)
}

func echo(in map[string]string) {
    fmt.Println(in)
}

最佳答案

可以使用不安全的包来做到这一点。

注意:我认为这不一定是一个好主意,可能正确的方法是迭代和复制,但因为它确实回答了所提出的问题......

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

关于dictionary - 在 Golang 中将命名类型映射[字符串]字符串转换为普通类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495784/

相关文章:

unit-testing - 如何在 Ubuntu 18.04 上使用 -msan 选项运行 go test?

inheritance - 使用设置保护值的 Golang 继承

postgresql - Postgres 数据类型 NUMERIC 可以存储有符号值吗?

Go map 和界面{}

python - 如何在 python 中将字符串或字典分成多行?

英语单词复数形式的Java API

Python 将字典视为字符串

java - containsKey 与网址不匹配

go - 从同一个项目中导入包

c# - 在C#中使用反射修改循环中的字段,扩展方法