结构切片之间的类型转换

结构切片之间的类型转换

本文介绍了Golang:结构切片之间的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题遵循 我的另一个问题.

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

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
}

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

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

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

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

谢谢.

推荐答案

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

You are currently dealing with two different types:

type Societe struct {
    Name string
}

还有匿名者:

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

如果没有标签,这两个将是相同的.Go 规范 声明(我的重点):

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

如果两个结构类型具有相同的字段序列,并且如果对应的字段具有相同的名称和相同的类型,和相同的标签.两个匿名字段被认为具有相同的名称.小写字段名称来自不同的包总是不同的.

因此,您无法在两者之间进行简单的转换.此外,您正在转换这两种类型的 slices 的事实使转换存在问题.我可以为您看到两个选项:

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:

通过迭代复制:

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

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

不安全的转换:

由于这两种类型具有相同的底层数据结构,因此可能会进行不安全的转换.
但是,这可能会在您以后爆发.请注意!

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

游乐场示例: http://play.golang.org/p/lfk7qBp2Gb

这篇关于Golang:结构切片之间的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:28