struct - 戈朗 : type conversion between slices of structs

标签 struct go type-conversion

此问题如下 another question of mine .

在以下测试代码中,我尝试将 res 转换为 ListSociete 时,我并没有完全弄清楚有什么问题:

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
}

[]struct{Name string} 是否不同于 []struct{Name string json:"a.name" } ?

或者 ListSociete 与 []struct{Name string} 不同吗?

谢谢。

最佳答案

您目前正在处理两种不同的类型:

type Societe struct {
    Name string
}

和匿名者:

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

如果没有标签,这两个将是相同的。 <强> Go Specifications 状态(我强调):

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.

所以,你不能在两者之间做简单的转换。此外,您正在转换这两种类型的 slice 这一事实会使转换出现问题。我可以为您看到两个选项:

通过迭代复制:

这是安全且推荐的解决方案,但它也更加冗长和缓慢。

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

不安全的转换:

由于两种类型具有相同的底层数据结构,因此有可能进行不安全的转换。
不过,这以后可能会在您面前爆发。警告!

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

Playground 示例: http://play.golang.org/p/lfk7qBp2Gb

关于struct - 戈朗 : type conversion between slices of structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642148/

相关文章:

C++ 结构 "Incomplete type is not allowed"

C - 结构问题 - 写作

c - 与 c 相比,Go 的二进制大小

date - Grails "Unparseable Date"错误

android - 通过 Intent 传递的 int 值在新 Activity 上返回 0

xml - 嵌套的 XML/JSON 结构标记,定义结构的正确方法是什么?

c++ - 使用 vector 和 struct 在 C++ 中获取错误

go - 从go程序中的其他文件访问对象

go - 运行存储在接口(interface){}中的任何函数

c++ - 具有类型转换的多态复制构造函数