此问题如下 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/