dtwknzk3764 2014-07-08 21:53
浏览 338
已采纳

Golang:结构切片之间的类型转换

This questions follows another question of mine.

I don't exactly get what is wrong with my attempt to convert res to a ListSociete in the following test code :

import (
    "errors"
    "fmt"
    "github.com/jmcvetta/neoism"
)

type Societe struct {
    Name string
}

type ListSociete []Societe

func loadListSociete(name string) (ListSociete, error) {
    db, err := neoism.Connect("http://localhost:7474/db/data")
    if err != nil {
        return nil, err
    }
    res := []struct {
        Name string `json:"a.name"`
    }{}
    cq := neoism.CypherQuery{
        Statement: `
            MATCH (a:Societe)
            WHERE a.name = {name}
            RETURN a.name
            `,
        Parameters: neoism.Props{"name": name},
        Result:     &res,
    }
    db.Cypher(&cq)
    if len(res) == 0 {
        return nil, errors.New("Page duz not exists")
    }
    r := res[0]
    return ListSociete(res), nil
}

Is a []struct{Name string} different from a []struct{Name string json:"a.name" } ?

Or is a ListSociete different from a []struct{Name string} ?

Thanks.

  • 写回答

2条回答 默认 最新

  • dplht39359 2014-07-08 22:49
    关注

    You are currently dealing with two different types:

    type Societe struct {
        Name string
    }
    

    and the anonymous one:

    struct {
        Name string `json:"a.name"`
    }
    

    These two would be identical if it wasn't for the tag. The Go Specifications states (my emphasis):

    Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Two anonymous fields are considered to have the same name. Lower-case field names from different packages are always different.

    So, you can't do a simple conversion between the two. Also, the fact that you are converting slices of the two types makes the conversion problematic. I can see two options for you:

    Copy through iteration:

    This is the safe and recommended solution, but it is also more verbose and slow.

    ls := make(ListSociete, len(res))
    for i := 0; i < len(res); i++ { 
        ls[i].Name = res[i].Name
    }
    return ls, nil
    

    Unsafe conversion:

    Since both types have the same underlying data structure, it is possible to do an unsafe conversion.
    This might however blow up in your face later on. Be warned!

    return *(*ListSociete)(unsafe.Pointer(&res)), nil
    

    Playground Example: http://play.golang.org/p/lfk7qBp2Gb

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)