Function

Golang 不能在 function 內定義 function

https://stackoverflow.com/questions/21961615/why-doesnt-go-allow-nested-function-declarations-functions-inside-functions

基本寫法

func (繼承的方法) funcName(參數)(回傳值型態) {

}

有關funcName前面的參數可參考:https://tour.golang.org/methods/1

參數傳遞方式區別(pass by pointer, pass by value)

http://goinbigdata.com/golang-pass-by-pointer-vs-pass-by-value/

多個 return 值

package main

import "fmt"

func test(x int) (int, int) {
    return x, x + x
}

func main() {
    person, testtt := test(5)
    fmt.Printf("%v\n", person)
    fmt.Printf("%v", testtt)
}

彈性多個 argument

宣告參數時用 ...,此參數本質上是個 slice,可以使用 for range 來走訪元素,可接受可變長度的參數只能有一個,而必須是最後一個參數

改變參數記憶體位置

宣告函式

以下來宣告函式變數

之後可存取記憶體位置

如果是一般func要用以下存取記憶體

匿名函式

將func當參數傳入func

以下寫一個forEach func

不指定 argument 型態

傳入空 interface

Last updated

Was this helpful?