這期內容當中小編將會給大家帶來有關怎么在Golang中對函數的參數進行傳遞,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創新互聯建站專注于企業全網整合營銷推廣、網站重做改版、崖州網站定制設計、自適應品牌網站建設、H5開發、商城建設、集團公司官網建設、成都外貿網站制作、高端網站制作、響應式網頁設計等建站業務,價格優惠性價比高,為崖州等各大城市提供網站開發制作服務。
默認情況下,Go編程語言使用調用通過值的方法來傳遞參數。在一般情況下,這意味著,在函數內碼不能改變用來調用所述函數的參數。考慮函數swap()的定義如下。
/* function definition to swap the values */func swap(int x, int y) int { var temp int temp = x /* save the value of x */ x = y /* put y into x */ y = temp /* put temp into y */ return temp;}
現在,讓我們通過使實際值作為在以下示例調用函數swap():
package main import "fmt" func main() { /* local variable definition */ var a int = 100 var b int = 200 fmt.Printf("Before swap, value of a : %d\n", a ) fmt.Printf("Before swap, value of b : %d\n", b ) /* calling a function to swap the values */ swap(a, b) fmt.Printf("After swap, value of a : %d\n", a ) fmt.Printf("After swap, value of b : %d\n", b )}func swap(x, y int) int { var temp int temp = x /* save the value of x */ x = y /* put y into x */ y = temp /* put temp into y */ return temp;}
讓我們把上面的代碼放在一個C文件,編譯并執行它,它會產生以下結果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200
這表明,參數值沒有被改變,雖然它們已經在函數內部改變。
通過傳遞函數參數,即是拷貝參數的地址到形式參數的參考方法調用。在函數內部,地址是訪問調用中使用的實際參數。這意味著,對參數的更改會影響傳遞的參數。
要通過引用傳遞的值,參數的指針被傳遞給函數就像任何其他的值。所以,相應的,需要聲明函數的參數為指針類型如下面的函數swap(),它的交換兩個整型變量的值指向它的參數。
/* function definition to swap the values */ func swap(x *int, y *int) { var temp int temp = *x /* save the value at address x */ *x = *y /* put y into x */ *y = temp /* put temp into y */ }
現在,讓我們調用函數swap()通過引用作為在下面的示例中傳遞數值:
package main import "fmt" func main() { /* local variable definition */ var a int = 100 var b int= 200 fmt.Printf("Before swap, value of a : %d\n", a ) fmt.Printf("Before swap, value of b : %d\n", b ) /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b) fmt.Printf("After swap, value of a : %d\n", a ) fmt.Printf("After swap, value of b : %d\n", b )} func swap(x *int, y *int) { var temp int temp = *x /* save the value at address x */ *x = *y /* put y into x */ *y = temp /* put temp into y */}
讓我們把上面的代碼放在一個C文件,編譯并執行它,它會產生以下結果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100
這表明變化的功能以及不同于通過值調用的外部體現的改變不能反映函數之外。
上述就是小編為大家分享的怎么在Golang中對函數的參數進行傳遞了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創新互聯行業資訊頻道。
名稱欄目:怎么在Golang中對函數的參數進行傳遞
轉載來于:http://m.2m8n56k.cn/article40/jdsoeo.html
成都網站建設公司_創新互聯,為您提供靜態網站、營銷型網站建設、虛擬主機、、網站建設、網站導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯