DAY 14
0
Modern Web

# 撰寫函式

``````package main

import (
"fmt"
)

func hello() {
fmt.Println("Hello Rookie")
}
func main() {
hello() // Hello Rookie
}
``````

``````package main

import (
"fmt"
)

func hello(name string) {
fmt.Println("Hello", name)
}
func main() {
hello("Jack") // Hello Jack
hello("Zhen") // Hello Zhen
}
``````

# 撰寫函式(輸入多個參數)

``````package main

import (
"fmt"
)

func hello(name1, name2 string) {
fmt.Println("Hello", name1, "and", name2)
}
func main() {
hello("Jack", "Zhen") // Hello Jack and Zhen
}
``````

# 撰寫函式(輸入不定長度參數)

Go 語言的函式也支援輸入不定長度的參數：

``````package main

import (
"fmt"
)

var total int
for _, xi := range x {
total += xi
}
fmt.Println(total)
}
func main() {
}
``````

# 撰寫函式(回傳return)

``````package main

import (
"fmt"
)

return x + y
}
func main() {
fmt.Println(add(1, 2) == 3) // true
}
``````

# 撰寫函式(回傳命名)

``````package main

import (
"fmt"
)

func add(x, y int) (z int){
z = x + y
return
}
func main() {
fmt.Println(add(1, 2) == 3) // true
}
``````

# init函式

init 函式是個特殊的函示，如果一段程式碼內包含著 init 函式，則在執行整個程式碼時，會優先值些 init裡的程式碼，通常需要初始化一些外部資源時，會將這些程式碼寫在init 函式裡，以下是 Go 官方網站的例子：

``````func init() {
if user == "" {
log.Fatal("\$USER not set")
}
if home == "" {
home = "/home/" + user
}
if gopath == "" {
gopath = home + "/go"
}
// gopath may be overridden by --gopath flag on command line.
flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH")
}
``````

golang後端入門分享30