dqef7931 2013-09-21 22:03
浏览 30
已采纳

这种“模式”背后的动机是什么?

I'm a bit confused when I see code such as:

bigBox := &BigBox{}
bigBox.BubbleGumsCount = 4          // correct...
bigBox.SmallBox.AnyMagicItem = true // also correct

Why, or when, would I want to do bigBox := &BigBox{} instead of bigBox := BigBox{} ? Is it more efficient in some way?

Code sample was taken from here.

Sample no.2:

package main

import "fmt"

type Ints struct {
  x int
  y int
}

func build_struct() Ints {
  return Ints{0,0}
}

func build_pstruct() *Ints {
  return &Ints{0,0}
}

func main() {
  fmt.Println(build_struct())
  fmt.Println(build_pstruct())
}

Sample no. 3: ( why would I go with &BigBox in this example, and not with BigBox as a struct directly ? )

func main() {
  bigBox := &BigBox{}
  bigBox.BubbleGumsCount = 4 
  fmt.Println(bigBox.BubbleGumsCount)
}

Is there ever a reason to call build_pstruct instead of the the build_struct variant? Isn't that why we have the GC?

  • 写回答

5条回答 默认 最新

  • dongzi9196 2013-09-25 10:16
    关注

    I figured out one motivation for this kind of code: avoidance of "struct copying by accident".


    If you use a struct variable to hold the newly created struct:

    bigBox := BigBox{}
    

    you may copy the struct by accident like this

    myBox := bigBox // Where you just want a refence of bigBox.
    myBox.BubbleGumsCount = 4
    

    or like this

    changeBoxColorToRed(bigBox)
    

    where changeBoxColorToRed is

    // It makes a copy of entire struct as parameter. 
    func changeBoxColorToRed(box bigBox){
        // !!!! This function is buggy. It won't work as expected !!!
        // Please see the fix at the end.
        box.Color=red
    }
    

    But if you use a struct pointer:

    bigBox := &BigBox{}
    

    there will be no copying in

    myBox := bigBox
    

    and

    changeBoxColorToRed(bigBox)
    

    will fail to compile, giving you a chance to rethink the design of changeBoxColorToRed. The fix is obvious:

    func changeBoxColorToRed(box *bigBox){
        box.Color=red
    }
    

    The new version of changeBoxColorToRed does not copy the entire struct and works correctly.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集