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
                        },
                        // ..
                    },
                },
            },
        },
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了