這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
關於參數傳遞,Golang文檔中有這麼一句:
after they are evaluated, the parameters of the call are passed by value to the
function and the called function begins execution.
函數調用參數均為值傳遞,不是指標傳遞或引用傳遞。經測試引申出來,當參數變數為指標或隱式指標類型,參數傳遞方式也是傳值(指標本身的copy)
Slice是最常用的資料結構之一,下面以Slice為例,解釋Golang的參數傳遞機制。
Slice資料結構如下:
範例程式碼:
package mainimport "fmt"func main(){ slice := make([]int, 3, 5) fmt.Println("before:", slice) changeSliceMember(slice) fmt.Println("after:", slice)}func changeSliceMember(slice []int) { if len(slice) > 1 { slice[0] = 9 }}
函數執行結果為:
befor:[0 0 0]after:[9 0 0]
解釋:
從資料結構圖中可看出,Slice可以理解成結構體類型,包含底層數組首元素地址、數組len、容量三個欄位,slice對象在參數傳值過程中,把三個欄位的值傳遞過去了,實際上changeSliceMember函數內slice在記憶體中的地址和main中的slice記憶體位址不一樣,只是欄位值是一樣的,而第一個欄位Pointer的值就是底層數組首元素地址,因此可以直接改變元素內容
可以與下面代碼做對比,理解:
package mainfunc main() { value := new(int) modifyFunc(value) println("main:", value)}func modifyFunc(value *int) { value = nil println("modifyFunc:", value)}
執行結果:
modifyFunc: 0x0main: 0xc820049f30
可以看出,即使傳值為指標,仍未改變變數value在main中的值,因為modifyFunc中value的值為指標,和main中的value值一樣,但是倆對象本身是兩個對象,讀者可以細細體會