「Golang筆記」Function

[參考]Appleboy於Udemy課程:Go 語言基礎實戰
https://www.udemy.com/golang-fight/learn/v4/overview

Function主要是用來將整體的程式碼做功能性的區分,降低整體程式碼的重複性,也提升程式碼的可讀性。

Golang的Function相較於其他的程式語言,我覺得最大的特點就是支持Multiple Return;例如當你建立一個公用Function供其他開發者使用時,你可以同時回傳兩個變數:一個是回傳值,另一個則是是否正常處理的布林值,如此當外部使用該Function的時候,就可以根據該布林值決定是否取該回傳值往下做處理。

Golang的Function可分為以下幾種:

  1. 單一回傳值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    package main

    import (
    "fmt"
    )

    func add(i, j float32) float32 {
    return i + j
    }
    func main() {
    fmt.Println(add(4.12, 5.67))
    }
    輸出結果
    9.79
  2. 多重回傳值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package main

    import (
    "fmt"
    )

    func div(divisor, dividend float32) (float32, bool) {
    if dividend == 0 {
    return 0, false
    }

    return divisor / dividend, true

    }
    func main() {

    if divResult, returnCode := div(4.12, 5.67); returnCode {
    fmt.Printf("The result of devision is %f", divResult)
    } else {
    fmt.Printf("Failed to get division result")
    }
    }

    輸出結果
    The result of devision is 0.726631

  3. 回傳Function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    package main

    import (
    "fmt"
    )

    func doAction(a, b float32, method string) func() string {
    if method == "add" {
    return func() string {
    return fmt.Sprintf("The add result is %f", a+b)
    }
    } else if method == "sub" {
    return func() string {
    return fmt.Sprintf("The add result is %f", a-b)
    }
    } else {
    return func() string {
    return fmt.Sprintln("The method parameter is invalid")
    }
    }
    }
    func main() {
    addMethod := doAction(1.11, 2.22, "add")
    subMethod := doAction(9.87, 6.54, "sub")
    devMethod := doAction(5.67, 7.43, "dev")

    fmt.Printf("Type of addMethod is %T \n", addMethod)
    fmt.Println(addMethod())
    fmt.Printf("Type of subMethod is %T \n", subMethod)
    fmt.Println(subMethod())
    fmt.Printf("Type of devMethod is %T \n", devMethod)
    fmt.Println(devMethod())
    }

    輸出結果
    Type of addMethod is func() string
    The add result is 3.330000
    Type of subMethod is func() string
    The add result is 3.330000
    Type of devMethod is func() string
    The method parameter is invalid

  4. Anonymous Function

0%