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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度