gpt4 book ai didi

go - 对指针和值参数新主义感到困惑

转载 作者:数据小太阳 更新时间:2023-10-29 03:07:26 24 4
gpt4 key购买 nike

我正在用 Go 编写一个 Web 应用程序并使用 Neo4j 数据库来存储数据。作为 Go 的 Neo4j API,我选择 neoism .

但是,请看下面的代码片段。

db, _ := neoism.Connect("http://localhost:7474/db/data")
// Create a node with a Cypher quer
// Issue a query
//
res1 := []struct {
A string `json:"n.email"`
}{}
cq1 := neoism.CypherQuery{
//Use backticks for long statements - Cypher is whitespace indifferent
Statement: `
MATCH (n:Account {email: {email}})
RETURN n.email
`,
Parameters: neoism.Props{"email": "hans@ueli.com"},
Result: &res1,
}
db.Cypher(&cq1)
fmt.Println(res1)

我在这里查询来自节点帐户的数据并得到结果返回,这里一切正常。第二个代码几乎相同,但我在这里直接创建(变量 res2)一个指针 slice 。

// Validate, if email already available in db
res2 := []*struct {
A string `json:"n.email"`
}{}
cq := &neoism.CypherQuery{
Statement: `
MATCH (n:Account {email: {email}})
RETURN n.email
`,
Parameters: neoism.Props{"email": "hans@ueli.com"},
Result: res2,
}
db.Cypher(cq)
fmt.Println(res2)

它们之间的区别是,我通过第一个样本得到了结果,但第二个没有。
结果:

[{hans@ueli.com}]
[]

这里的指针 res2 有什么问题?

最佳答案

来自新主义文档:

Result must be a pointer to a slice of structs - e.g. &[]someStruct{}

没有提到结构指针的 slice ,所以我假设你的 slice 是空的,因为函数不需要指针,所以它不能在 slice 中放任何东西。

我在给 sqlx.Query 错误类型的 slice 时遇到了同样的行为。第一次没有错误是非常令人沮丧的,但它很快就成为一种条件反射。

关于go - 对指针和值参数新主义感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25201001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com