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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀