DAY 9
1
Modern Web

# Function(前)

Go的Function方式有幾種

## func方法

``````func foo(name string) {
fmt.Println("Hi " + name)
}
``````

## fucn方法(多個傳入值)

``````func foo(name1 string, name2 string) {
fmt.Println("Hi " + name1 + ", " + name2)
}
``````

``````func foo(name1, name2 string) {
fmt.Println("Hi " + name1 + ", " + name2)
``````

## func方法(retuen)

``````func foo(name string) string {
var str = "Hi " + name
return str
}
``````

## func方法(return命名)

Go可以直接在function的回傳區塊命名回傳變數，同樣括號內前者是名稱，後者是型態，return之後還不用填變數

``````func foo(name string) (str string) {
str = "Hi " + name
return
}
``````

## func方法(多重return)

``````func foo(x, y int) (int, int) {
return x + y, x - y
}
``````

## func方法(多傳入值)

``````func total(x ...int) int {
var t int
for _, n := range x {
t += n
}
return t
}
``````

## func方法(傳入slice)

slice是類似矩陣的東西，後面幾篇會介紹

``````func total(x []int) int {
var t int
for _, n := range x {
t += n
}
return t
}
``````

## 當變數宣告

``````foo := func() {
fmt.Println("Hi " + name)
}
``````

## function回傳function

``````func foo() func() string {
return func() string {
return "I don't know what is this mean"
}
}
``````

### 1 則留言

1
shewer
iT邦新手 5 級 ‧ 2019-03-20 21:52:36

1 例如 return 計算函式
2 建立類似函式內靜態變數

### 1.

``````package main
import (
"fmt"
)

func option( op string ) func(a int,b int) int {
swich op {
case "+":
return func(a int,b int) int {
return a+b;
}
// .......
}
}

``````

### 2.

``````pack main
func Count_init( num int) int {
count := num
return func() int {
count++
return count
}
}

func main() {
count = Count_init(3)
for j:=10; j>0;j-- {
fmt.Println("count number:" , count() )
}
}

``````