# 函式入門

``````func funcName(param1 type1, param2 type2) (return1 type1, return2 type2) {
// 一些程式碼...
return value1, value2
}
``````

# 定義函式

``````package main

import "fmt"

func Gcd(m, n int) int {
if n == 0 {
return m
} else {
return Gcd(n, m%n)
}
}

func main() {
fmt.Printf("Gcd of 10 and 4: %d\n", Gcd(10, 4)) // 2
}
``````

``````package main

import "fmt"

func Gcd(m, n int) (gcd int) {
if n == 0 {
gcd = m
} else {
gcd = Gcd(n, m%n)
}
return
}

func main() {
fmt.Printf("Gcd of 10 and 4: %d\n", Gcd(10, 4)) // 2
}
``````

# 多個傳回值

Go 中允許多個傳回值，例如，定義一個函式，可搜尋 slice 的元素中是否指定的子字串，若有就傳回元素索引位置與字串，若無就傳回 -1 與空字串：

``````package main

import "fmt"
import "strings"

func FirstMatch(elems []string, substr string) (int, string) {
for index, elem := range elems {
if strings.Contains(elem, substr) {
return index, elem
}
}
return -1, ""
}

func main() {
names := []string{"Justin Lin", "Monica Huang", "Irene Lin"}
if index, name := FirstMatch(names, "Huang"); index == -1 {
fmt.Println("找不到任何東西")
} else {
fmt.Printf("在索引 %d 找到 \"%s\"\n", index, name)
}
}
``````

``````_, name := FirstMatch(names, "Huang")
``````

``````package main

import "fmt"
import "errors"

func Div(x, y int) (int, error) {
if y == 0 {
return 0, errors.New("division by zero")
}
return x / y, nil
}

func main() {
if result, err := Div(10, 5); err == nil {
fmt.Printf("10 / 5 = %d\n", result)
} else {
fmt.Println(err)
}
}
``````

``````func Open(name string) (file *File, err error)
``````

``````file, err := os.Open("file.go")
if err != nil {
log.Fatal(err)
}
``````

# 可變參數

``````package main

import "fmt"

func Sum(numbers ...int) int {
var sum int
for _, number := range numbers {
sum += number
}
return sum
}

func main() {
fmt.Println(Sum(1, 2))          // 3
fmt.Println(Sum(1, 2, 3))       // 6
fmt.Println(Sum(1, 2, 3, 4))    // 10
fmt.Println(Sum(1, 2, 3, 4, 5)) // 15
}
``````

``````package main

import "fmt"

func Sum(numbers ...int) int {
var sum int
for _, number := range numbers {
sum += number
}
return sum
}

func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(Sum(numbers...)) // 15
}
``````

# 函式與指標

Go 語言有指標，因此，在變數傳遞就多了一種選擇，直接來看個例子，以下的執行結果會顯示 1：

``````package main

import "fmt"

n = n + 1
}

func main() {
number := 1
fmt.Println(number) // 1
}
``````

``````package main

import "fmt"