我正在尝试用我的 struct granJoin切片填充grantJointResponse,它来自查询的数据,切片可以有不同的大小。这在 Python 或 JS 等语言中很容易,但我在 Golang 中尝试了几种组合,但无法使其工作。我的压力与切片的声明有关,我尝试过grantJointResponse[contadorOwners] = make(granJoin, 0),grantJointResponse := [][]granJoin{},grantJointResponse[contadorOwners] = granJoin{}而且我无法弄清楚,很可能这很容易而且我没有看到它(我对Golang有点陌生)。这个当前版本得到一个grantJointResponse[contadorOwners] = []granJoin{auxJoin} 中的索引超出范围。因此,如果有人知道如何做到这一点,将不胜感激:)
import (
"fmt"
.
.
.
"log"
_ "github.com/lib/pq"
"database/sql"
)
type granJoin struct{
property_id sql.NullInt64
owner_id sql.NullInt64
}
rows, err := dbLeasity.Query(contractsQuery)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
current_owner_id := int64(-1)
contadorOwners := -1
cntProp := 0
var grantJointResponse [][]granJoin
for rows.Next() {
var auxJoin granJoin
if err := rows.Scan(&auxJoin.owner_id, &auxJoin.property_id); err != nil {
log.Fatal(err)
}
if (auxJoin.owner_id.Valid){
if (current_owner_id == -1){
grantJointResponse = [][]granJoin{{auxJoin}}
}
if (auxJoin.owner_id.Int64 != current_owner_id){
cntProp = 0
contadorOwners++
current_owner_id = auxJoin.owner_id.Int64
if (current_owner_id != -1){
grantJointResponse[contadorOwners] = []granJoin{auxJoin}
}
}
if (cntProp != 0){
grantJointResponse[contadorOwners] = append(grantJointResponse[contadorOwners], auxJoin)
}
cntProp++
}
}
我希望创造这样的东西:
// Data that will be in the rows
granJoin1 = { {true, 1}, {true, 10} }
granJoin2 = { {true, 2}, {true, 11} }
granJoin3 = { {true, 2}, {true, 12} }
granJoin4 = { {true, 2}, {true, 13} }
granJoin5 = { {true, 3}, {true, 14} }
granJoin6 = { {true, 3}, {true, 15} }
//The way I need to be on the Slice of Slices
grantJointResponse := {
{granJoin1},
{granJoin2, granJoin3, granJoin4},
{granJoin5, granJoin6}
}
忽然笑
相关分类