我正在使用两个库,其中一个定义了一种类型:
type Attrs map[string]string
而另一个定义:
type StringMap map[string]string
第一个库中的函数返回一个[]Attrs
,而另一个库所需的结构有一个需要设置的字段[]StringMap
。尝试使用简单的赋值或 ([]StringMap)(attrs)
形式的强制转换,只会导致错误:
./wscmd.go:8:22: cannot convert attrs (type []mpd.Attrs) to type []StringMap
那么,如何将它们连接起来呢?
编辑: 好的,显然这是语言限制(嘘)。它可以用不安全的指针放在一边吗?
最佳答案
你可以这样做,但它绕过了 Go 的类型安全,这可能会导致问题,具体取决于实现类型。
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
type Attrs map[string]string
type StringMap map[string]string
a := Attrs{"key1": "val1", "key2": "val2"}
b := Attrs{"key3": "val3", "key4": "val4"}
attrs := []Attrs{a, b}
// This is what you're asking for, keep in mind this circumvents the type safety provided by go
sh := *(*reflect.SliceHeader)(unsafe.Pointer(&attrs))
unsafeStrMaps := *(*[]StringMap)(unsafe.Pointer(&sh))
fmt.Println(unsafeStrMaps)
// This would be the preferred way of casting the array
strMaps := []StringMap{}
for _, v := range attrs {
strMaps = append(strMaps, StringMap(v))
}
fmt.Println(strMaps)
}
对于类型安全来说,只迭代 []Attrs
slice 并附加到 []StringMap
会好得多。
关于go - 转换兼容但不同的 map slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517103/