dpjw67160 2018-06-04 15:49
浏览 17
已采纳

当我将变量传递给golang中的私有方法时,它会创建一个新实例吗?

If I have main function:

var a = "foo"
modify(a)
fmt.Println(a)

where

func modify(s string) error {
  s = "bar"
}

will the result be "foo" or "bar"?

  • 写回答

1条回答 默认 最新

  • doudi4014 2018-06-04 18:58
    关注

    None. It won't compile because neither 'foo' nor 'bar' is a single character. But let's say you used double quotes instead.

    In Golang, arguments are passed by value (they are copied to the new place in memory - stack or heap), and it does not matter whether it is a private or a public method or arbitrary function. The new instance is modified. The result of your example will be "foo".

    In order to modify variable lying outside of the function, you have to explicitly pass the pointer pointing to such variable.

    func modify(s *string) {
      *s = "bar"
    }
    
    ...
    
    var a = "foo"
    modify(&a)
    println(a) // will print "bar"
    

    In this case pointer itself is passed by values (it is copied) but its value (the address of a) still points to the same variable. So the a can by modified through the pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 三菱FX系列PLC串口指令
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型