Golang中參數傳遞詳解

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

關於參數傳遞,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值一樣,但是倆對象本身是兩個對象,讀者可以細細體會

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.