function 的結構如下,使用 func 宣告且需要有名稱、輸入參數、回傳結果跟 function 主體
func name(parameter-list) (result-list) {
body
}
輸入參數如果是同型別的話可以簡化成 add(x, y int).輸入參數沒用到的話可以用 _ 省略.
回傳結果可以給一個變數,這樣在 function 裡就可以不用最後再 return 一個值.
package main
import (
"crypto/rand"
"fmt"
"math/big"
mathRand "math/rand"
"time"
)
func main() {
fmt.Println(add(1, 2)) // 3
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) {
ret, _ = rand.Int(rand.Reader, big.NewInt(int64(seed)))
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) {
number, _ := rand.Int(rand.Reader, big.NewInt(int64(seed)))
ret = sayHello("Daniel") + ",your number is " + strconv.FormatInt(number.Int64(), 10)
return
}
像 strings.Map 是把 funtcion 當參數傳遞,第 2 個參數字串會根據第 1 個參數的方法來做轉換
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() {
sum, message := add(5, 10)
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
}