Go函數實例

函數是Go語言編程的核心,這裏將通過以下幾個不同的例子來了解和學習函數的使用。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

這裏實現一個函數,它接受兩個int類型參數並將它們的和作爲一個int返回。
在Go編程中需要顯式返回,即它不會自動返回最後一個表達式的值。

當有多個相同類型的連續參數時,可以省略類型參數的類型名稱,直到聲明該類型的最後一個參數。

使用name(args)調用函數,正如所期望的調用方式那樣。

Go函數還有幾個其他功能。一個是多個返回值,在接下來實現中我們來看看。

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)
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run functions.go
1+2 = 3
1+2+3 = 6