函數(shù)是Go語(yǔ)言編程的核心,這里將通過(guò)以下幾個(gè)不同的例子來(lái)了解和學(xué)習(xí)函數(shù)的使用。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
這里實(shí)現(xiàn)一個(gè)函數(shù),它接受兩個(gè)int類型參數(shù)并將它們的和作為一個(gè)int返回。
在Go編程中需要顯式返回,即它不會(huì)自動(dòng)返回最后一個(gè)表達(dá)式的值。
當(dāng)有多個(gè)相同類型的連續(xù)參數(shù)時(shí),可以省略類型參數(shù)的類型名稱,直到聲明該類型的最后一個(gè)參數(shù)。
使用name(args)調(diào)用函數(shù),正如所期望的調(diào)用方式那樣。
Go函數(shù)還有幾個(gè)其他功能。一個(gè)是多個(gè)返回值,在接下來(lái)實(shí)現(xiàn)中我們來(lái)看看。
functions.go的完整代碼如下所示 -
package main
import "fmt"
// Here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {
// Go requires explicit returns, i.e. it won't
// automatically return the value of the last
// expression.
return a + b
}
// When you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusPlus(a, b, c int) int {
return a + b + c
}
func main() {
// Call a function just as you'd expect, with
// `name(args)`.
res := plus(1, 2)
fmt.Println("1+2 =", res)
res = plusPlus(1, 2, 3)
fmt.Println("1+2+3 =", res)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run functions.go
1+2 = 3
1+2+3 = 6