gpt4 book ai didi

go - 我怎样才能把一个对象放在golang的对象中

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

我正在尝试做的是将来 self 的数据库的整个对象加载到一个对象中。

type RatingPK struct {
ratingsPK Rating
}

func (r *RatingPK) Init(rg Rating) {
r.ratingsPK = rg
}

func searchUserRatings(id string)(ratings []Rating) {

rows, err := db.Query("SELECT * FROM ratings WHERE userId = ?", id)

if err != nil {
return
}

for rows.Next() {

rate := Rating{}

err = rows.Scan(&rate.MovieId, &rate.UserId, &rate.RatingId, &rate.Rating, &rate.Timestamp)

if err != nil {
return
}

r := RatingPK{}
r.Init(rate)
ratings = append(ratings, r)
}

defer rows.Close()

return
}

这段代码给了我这个结果:

   [{
"rating_id": 593,
"userId": 2,
"movieId": 93,
"rating": 3,
"timestamp": "0000-00-00"
},
{
"rating_id": 616,
"userId": 2,
"movieId": 94,
"rating": 3,
"timestamp": "0000-00-00"
}]

现在我要做的是获取数组中的每个对象并将其放入另一个对象中,所需的结果将是这样的:

[{"ratingsPK": {
"rating_id": 593,
"userId": 2,
"movieId": 93,
"rating": 3,
"timestamp": "0000-00-00"
}},
{"ratingsPK": {
"rating_id": 616,
"userId": 2,
"movieId": 94,
"rating": 3,
"timestamp": "0000-00-00"
}}]

有什么办法可以实现吗?

最佳答案

您可以循环执行以下操作

type RatingPK struct {
ratingsPK Rating
}

func (r *RatingPK) Init(rg Rating) {
r.ratingsPK = rg
}

func searchUserRatings(id string) (ratings []RatingPK) {

rows, err := db.Query("SELECT * FROM ratings WHERE userId = ?", id)

if err != nil {
return
}

var myarray []string

for rows.Next() {
rate := Rating{}
err = rows.Scan(&rate.MovieId, &rate.UserId, &rate.RatingId, &rate.Rating, &rate.Timestamp)
if err != nil {
return
}
r := RatingPK{}
r.Init(rate)
ratings = append(ratings, r)
}

defer rows.Close()
return
}

关于go - 我怎样才能把一个对象放在golang的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42043219/

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