- Go 教程
- Go - 首頁
- Go - 概述
- Go - 環境設定
- Go - 程式結構
- Go - 基本語法
- Go - 資料型別
- Go - 變數
- Go - 常量
- Go - 運算子
- Go - 決策
- Go - 迴圈
- Go - 函式
- Go - 作用域規則
- Go - 字串
- Go - 陣列
- Go - 指標
- Go - 結構體
- Go - 切片
- Go - 範圍
- Go - 對映
- Go - 遞迴
- Go - 型別轉換
- Go - 介面
- Go - 錯誤處理
- Go 有用資源
- Go - 常見問題解答
- Go - 快速指南
- Go - 有用資源
- Go - 討論
Go - 傳值呼叫
按值傳遞函式引數的方法將引數的實際值複製到函式的形式引數中。在這種情況下,在函式內部對引數所做的更改不會影響引數。
預設情況下,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
這表明值沒有變化,儘管它們在函式內部已經被更改。
go_functions.htm
廣告