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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?