如何在golang中将对象放入对象中

时间:2017-02-04 17:18:53

标签: go

我要做的是将来自我的数据库的整个对象加载到对象中。

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"
  }}]

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

您可以循环并执行以下操作

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
}

答案 1 :(得分:0)

这是一个简短的例子,可以帮助您了解如何使用嵌套结构;)

package main

import (
    "fmt"
)

type nameType struct {
    firstName string
    lastName string
}

type student struct {
    name nameType
    age int
}

func main() {
    bob := student{nameType{"bob", "dope"}, 18}

    fmt.Println(bob.name.firstName)
}

你可以在这里测试一下;)

https://play.golang.org/p/ft9PGrlrrx