golang pointers on pointers as function parameters

前端 未结 3 728
夕颜
夕颜 2021-01-30 05:38

I have the following function:

func addCatsToMap(m map[string][]CatHouse, meowId int, treats Set, dog *Dog) {

//if (complicated thing) add Cat to m

}
<         


        
3条回答
  •  一生所求
    2021-01-30 06:20

    Pass by reference is a language thing, nothing in Go is "pass by reference". Pass by reference means the assignment operator can change the original value when use alone. However, there are reference types such as maps and pointers which point somewhere. Using the assignment operator on them will not modify the original unless you use other operators such as the map index and the * operator.

    You are correct that your map m is a reference type and therefore like a pointer. Any changes to the map except replacing the map will modify the original.

    m["whatever"] = 2           // Modifies the original map
    m = anothermap              // Does not modify the original map
    

    If there was true "pass by reference", the second example would modify the original map.

    Passing a pointer, as you do with dog allows you to modify the original. If you call any pointer methods or use the * operator, the original will change. In your example, a pointer may not have been needed. If Dog is small, it may be easier to just pass a copy. It is up to the programmer to determine when it is a good time to use a pointer.

    Set is not passed by reference. Interfaces are not references. While it is true that internally in the 6g compiler an interface uses pointers, the interface itself does not act like one. Passing an interface, no matter of the size of the object it contains, is as cheap as passing a pointer using the 6g compiler. However, there is no way to modify the original value of an interface as you can with pointers and maps.

    Although you can not modify the original interface passed, the interface can contain a pointer type. In that case it would act just like the dog pointer where the calling of certain methods can modify the original. For your particular Set interface, I would guess it contains a pointer type based on the method names. So when you call set.Add(whatever), it will change the internal data of the original.

提交回复
热议问题