douqiao2008
2015-02-12 13:04
浏览 81

在golang中的嵌套结构中初始化结构数组

I am wondering how can I define and initialize and array of structs inside a nested struct, for example:

type State struct {
    id string `json:"id" bson:"id"`
    Cities 
}

type City struct {
    id string `json:"id" bson:"id"`
}

type Cities struct {
    cities []City
}

Now how can I Initialize such a structure and if someone has a different idea about how to create the structure itself.

Thanks

图片转代码服务由CSDN问答提供 功能建议

我想知道如何在嵌套结构中定义和初始化结构以及结构数组,例如:

  type状态结构{
 id字符串`json:“ id” bson:“ id”`
城市
} 
 
type城市结构{
 id字符串`json  :“ id” bson:“ id”`
} 
 
type城市结构{
城市[]城市
} 
   
 
 

现在我该如何 初始化这样的结构,如果有人对如何自己创建结构有不同的想法。

谢谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyan1841 2015-02-12 13:11
    已采纳

    In your case the shorthand literal syntax would be:

    state := State {
        id: "CA",
        Cities:  Cities{
            []City {
                {"SF"},
            },
        },
    }
    

    Or shorter if you don't want the key:value syntax for literals:

    state := State {
        "CA", Cities{
            []City {
                {"SF"},
            },
        },
    }    
    

    BTW if Cities doesn't contain anything other than the []City, just use a slice of City. This will lead to a somewhat shorter syntax, and remove an unnecessary (possibly) layer:

    type State struct {
        id string `json:"id" bson:"id"`
        Cities []City
    }
    
    type City struct {
        id string `json:"id" bson:"id"`
    }
    
    
    func main(){
        state := State {
            id: "CA",
            Cities:  []City{
                 {"SF"},
            },
        }
    
        fmt.Println(state)
    }
    
    点赞 打赏 评论
  • ds11111111111111111 2015-02-12 13:11

    Full example with everything written out explicitly:

    state := State{
        id: "Independent Republic of Stackoverflow",
        Cities: Cities{
            cities: []City{
                City{
                    id: "Postington O.P.",
                },
            },
        },
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题