drba1172 2017-11-14 22:30
浏览 12
已采纳

通过转到函数中的引用和值

I am a bit confused about passing by reference and value in Go.

I've seen this explained of the * in front of a type.

  • in front of a type name, means that the declared variable will store an address of another variable of that type (not a value of that type).

This just doesn't make sense to me.

In Java if I was passing a Database instance into a function I would do

 databaseFunction(DatabaseType db) {
      // do something
}

However in the go example I have it's passed like so.

func PutTasks(db *sql.DB) echo.HandlerFunc {

}

Why do we need to have the asterisk in front of the type?

According to this cheat sheet, I found.

func PrintPerson(p *Person) ONLY receives the pointer address (reference)

I don't understand why I would only want to send a pointer address as a parameter.

  • 写回答

2条回答 默认 最新

  • dongyingtang3803 2017-11-14 22:34
    关注

    First, Go technically has only pass-by-value. When passing a pointer to an object, you're passing a pointer by value, not passing an object by reference. The difference is subtle but occasionally relevant. For example, you can overwrite the pointer value which has no impact on the caller, as opposed to dereferencing it and overwriting the memory it points to.

    // *int means you *must* pass a *int (pointer to int), NOT just an int!
    func someFunc(x *int) {
        *x = 2 // Whatever variable caller passed in will now be 2
        y := 7
        x = &y // has no impact on the caller because we overwrote the pointer value!
    }
    

    As to your question "Why do we need to have the asterisk in front of the type?": The asterisk indicates that the value is of type pointer to sql.DB, rather than a value of type sql.DB. These are not interchangeable!

    Why would you want to send a pointer address? So that you can share the value between the caller of a function and the function body, with changes made inside the function reflected in the caller (for example, a pointer is the only way that a "setter" method can work on an object). While Java passes objects by reference always, Go passes by value always (i.e. it creates a copy of the value in the function); if you pass something to a function, and that function modifies that value, the caller won't see those changes. If you want changes to propogate outside the function, you must pass a pointer.

    See also: the Go tour section on Pointers, the Go spec section on pointers, the Go spec section on the address operators

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

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题