dtpfia3334 2017-10-01 21:30
浏览 54
已采纳

投射兼容但不同的地图片段

I'm working with two libraries, and one defines a type:

type Attrs map[string]string

while the other defines:

type StringMap map[string]string

A function from the first library returns an []Attrs, and struct required by the other has a field as []StringMap which needs to be set. Attempting to either use a simple assignment, or a cast in the form of ([]StringMap)(attrs), just results in an error:

./wscmd.go:8:22: cannot convert attrs (type []mpd.Attrs) to type []StringMap

So, how can those be bridged?

Edit: Ok, apparently this is a language limitation (booo-hooo). Can it be stepped aside with unsafe pointers?

  • 写回答

1条回答 默认 最新

  • dongsi3826 2017-10-01 22:07
    关注

    You can do this, but it circumvents Go's type safety, which can lead to trouble depending on implementation type.

    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)
    }
    

    It is much better for type safety to just iterate the []Attrs slice and append to a []StringMap.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?