Go語言中函數(shù)的參數(shù)傳遞與調(diào)用的基本方法
按值傳遞函數(shù)參數(shù),是拷貝參數(shù)的實際值到函數(shù)的形式參數(shù)的方法調(diào)用。在這種情況下,參數(shù)在函數(shù)內(nèi)變化對參數(shù)不會有影響。
默認情況下,Go編程語言使用調(diào)用通過值的方法來傳遞參數(shù)。在一般情況下,這意味著,在函數(shù)內(nèi)碼不能改變用來調(diào)用所述函數(shù)的參數(shù)??紤]函數(shù)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;
}
現(xiàn)在,讓我們通過使實際值作為在以下示例調(diào)用函數(shù)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文件,編譯并執(zhí)行它,它會產(chǎn)生以下結(jié)果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200
這表明,參數(shù)值沒有被改變,雖然它們已經(jīng)在函數(shù)內(nèi)部改變。
通過傳遞函數(shù)參數(shù),即是拷貝參數(shù)的地址到形式參數(shù)的參考方法調(diào)用。在函數(shù)內(nèi)部,地址是訪問調(diào)用中使用的實際參數(shù)。這意味著,對參數(shù)的更改會影響傳遞的參數(shù)。
要通過引用傳遞的值,參數(shù)的指針被傳遞給函數(shù)就像任何其他的值。所以,相應(yīng)的,需要聲明函數(shù)的參數(shù)為指針類型如下面的函數(shù)swap(),它的交換兩個整型變量的值指向它的參數(shù)。
/* 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 */
}
現(xiàn)在,讓我們調(diào)用函數(shù)swap()通過引用作為在下面的示例中傳遞數(shù)值:
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文件,編譯并執(zhí)行它,它會產(chǎn)生以下結(jié)果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100
這表明變化的功能以及不同于通過值調(diào)用的外部體現(xiàn)的改變不能反映函數(shù)之外。
相關(guān)文章
基于Golang實現(xiàn)Redis分布式鎖解決秒殺問題
這篇文章主要給大家介紹了使用Golang實現(xiàn)Redis分布式鎖解決秒殺問題,文中有詳細的代碼示例供大家參考,具有一定的參考價值,需要的朋友可以參考下2023-08-08VSCode Golang dlv調(diào)試數(shù)據(jù)截斷問題及處理方法
這篇文章主要介紹了VSCode Golang dlv調(diào)試數(shù)據(jù)截斷問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06Go語言for range(按照鍵值循環(huán))遍歷操作
這篇文章主要介紹了Go語言for range(按照鍵值循環(huán))遍歷操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12