doupian6118 2017-02-28 15:51
浏览 95
已采纳

对象Golang中的对象中的对象

I'm attempting to create nested objects in mongoDB with no luck the format I am trying to achieve is as follows

 "Courses":{
    "Date":{
      "CourseName"  :{
                "hole 1"{

                }
                "hole 2"{

                }
                ...so on until 18 
               }//coursename
             }//date 
          }//courses

I've tried and succeeded with getting the date object within course by doing the following:

u := req.FormValue("username")
co := req.FormValue("course")
d := req.FormValue("date")

ng := nGame{Username: u, Course: co, Dates: d}
cn := courseName{CName: co}
query := bson.M{"username": u}
update := bson.M{"$push": bson.M{"Course": bson.M{ng.Dates: cn}}}  
err = c.Update(query, update)

The date object has the course name inside it what i'm trying to do is make course name another object which then I can insert the hole object.

The Structs i'm using are as follows:

type (
nGame struct {
    Username string
    Course   string
    Location string
    Dates    string
}
)
type (
courseName struct {
    CName string
}
)
  • 写回答

1条回答 默认 最新

  • douhanxujiuji6098 2017-02-28 15:59
    关注

    Your described structure, as I understand it, can be represented in Go as follows:

    type Hole struct {
        // Whatever you want here
    }
    
    type Course struct {
        Hole1 Hole `json:"hole 1"`
        Hole2 Hole `json:"hole 2"`
        // ...
        Hole18 Hole `json:"hole 18"`
    }
    
    type Courses struct {
        //  Date       CourseName
        map[string]map[string]Course
    }
    

    I would suggest, however, using an 18-element array for your holes, but that's up to you:

    type Course struct {
        Holes [18]Hole
    }
    

    Then you can instantiate one of these trees as (using a [18]Hole array; adjust accordingly if you use a different implementation):

    courses := Courses{
        map[string]map[string]Course{
            "2017-01-01": map[string]Course{
                "Bob's Course": Course{
                    [18]Hole{
                        Hole{
                          // Hole 1
                        },
                        Hole{
                          // Hole 2
                        },
                        // ..
                    },
                },
            },
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改