DAY 12
0
Software Development

## Go day 12 (function)

### function

function 的結構如下，使用 func 宣告且需要有名稱、輸入參數、回傳結果跟 function 主體

``````func name(parameter-list) (result-list) {
body
}
``````

``````package main

import (
"crypto/rand"
"fmt"
"math/big"
mathRand "math/rand"
"time"
)

func main() {
fmt.Println(randomNum(100, 3)) // 66
fmt.Println(mathRandom(100))   // 2813524261773535146

}
func add(x int, y int) int {
return x + y
}
func randomNum(seed, _ int) (ret *big.Int) {
return
}
func mathRandom(seed int) (ret int) {
mathRand.Seed(int64(time.Now().UnixNano()))
ret = mathRand.Int()
return
}

``````

``````sayHello := func(name string) {
fmt.Println("Hello " + name)
}
sayHello("Daniel") // Hello Daniel
``````

``````package main

import (
"crypto/rand"
"fmt"
"math/big"
"strconv"
)

func main() {
sayHello := func(name string) string {
return "Hello " + name
}
fmt.Println(randomNum(100, 1, sayHello)) // Hello Daniel,your number is 75
}

func randomNum(seed, _ int, sayHello func(string) string) (ret string) {
ret = sayHello("Daniel") + ",your number is " + strconv.FormatInt(number.Int64(), 10)
return
}

``````

``````package main

import (
"fmt"
"strings"
)

func main() {
trans := func(r rune) rune {
if r == 'A' || r == 97 {
return '*'
}
return r
}
retstr := strings.Map(trans, "ABCDEabcde")
fmt.Println(retstr) // *BCDE*bcde
}

``````

function 回傳多個結果

``````package main

import (
"fmt"
)

func main() {
fmt.Println(sum)     // 15
fmt.Println(message) // High
}

func add(x, y int) (retSum int, message string) {
sum := x + y
retSum = sum
if sum > 10 {
message = "High"
} else {
message = "Low"
}
return
}

``````

``````package main

import (
"fmt"
)

func main() {
fmt.Println(sum())        // 0
fmt.Println(sum(1))       // 1
fmt.Println(sum(1, 2))    // 3
fmt.Println(sum(1, 2, 3)) // 6
}

func sum(nums ...int) int {
sum := 0
for _, num := range nums {
sum += num
}
return sum
}

``````

``````package main

import "fmt"

func main() {
sum := 10
func(num int) { sum += num }(3) // 有參數呼叫
func() { sum -= 5 }() // 無參數呼叫
func() { sum *= 2 }()
fmt.Println(sum) // 16
}

``````