douchan0523 2014-03-29 22:33
浏览 36
已采纳

在go中初始化多个结构

I need to initialise multiple struct variables

Let's say the struct is

type Foo struct {
  a int
  b *Foo
}

And let's say I want to initialise 5 of those. Is there a cleaner way of doing it than below fragment multiple times?

s0 := &Foo{}
s1 := &Foo{}
s2 := &Foo{}

something like

var a, b, c, d int

Thanks for help! : )

  • 写回答

4条回答 默认 最新

  • dongtang6718 2014-03-30 04:22
    关注

    You can put them in one statement if you want:

    s0, s1, s2 := new(Foo), new(Foo), new(Foo)
    

    You can also do this:

    var s0, s1, s2 Foo
    

    And then use &s0, &s1 and &s2 subsequently instead of s0, s1 and s2.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部