dongtou2097 2014-02-27 23:20
浏览 66
已采纳

在Go中初始化结构时使用new与{}

So i know in go you can initialize a struct two different ways in GO. One of them is using the new keyword which returns a pointer to the struct in memory. Or you can use the { } to make a struct. My question is when is appropriate to use each? Thanks

  • 写回答

3条回答 默认 最新

  • doupeng5320 2014-02-28 00:06
    关注

    I prefer {} when the full value of the type is known and new() when the value is going to be populated incrementally.

    In the former case, adding a new parameter may involve adding a new field initializer. In the latter it should probably be added to whatever code is composing the value.

    Note that the &T{} syntax is only allowed when T is a struct, array, slice or map type.

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

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部