Go learning note 04 function

Posted by Gath on Tue, 03 Dec 2019 15:48:39 +0100

Catalog

Function definition

Function definitions are similar to variable definitions,

func function_name(var1, var2, var3, ...) (return_type1, return_type1, ...) {
    //function body
}

Example of function

package main

import (
    "fmt"
    "math"
    "reflect"
    "runtime"
)

//Function can have multiple parameters and multiple return values
func eval(a, b int, op string) (int, error) {
    switch op {
    case "+":
        return a + b, nil
    case "-":
        return a - b, nil
    case "*":
        return a * b, nil
    case "/":
        //The function div() has two return values. If one is not used, it can be replaced by ""
        q, _ := div(a, b)
        return q, nil
    default:
        return 0, fmt.Errorf(
            "unsupported operation: %s", op)
    }
}

//You can name the return value, but it is only recommended for very simple functions
func div(a, b int) (q, r int) {
    return a / b, a % b
}

//Function can be an argument to another function
func apply(op func(int, int) int, a, b int) int {
    
    //Get pointer to function
    p := reflect.ValueOf(op).Pointer()
    //Get function name
    opName := runtime.FuncForPC(p).Name()
    fmt.Printf("Calling function %s with args "+
        "(%d, %d)\n", opName, a, b)

    return op(a, b)
}

//Define variable parameters
func sum(numbers ...int) int {
    s := 0
    //Range get variable parameter range
    for i := range numbers {
        s += numbers[i]
    }
    return s
}

func swap(a, b int) (int, int) {
    return b, a
}

func main() {
    fmt.Println("Error handling")
    if result, err := eval(3, 4, "x"); err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println(result)
    }
    q, r := div(13, 3)
    fmt.Printf("13 div 3 is %d mod %d\n", q, r)
    
    //Function programming, you can directly define an anonymous function in an expression
    fmt.Println("pow(3, 4) is:", apply(
        func(a int, b int) int {
            return int(math.Pow(
                float64(a), float64(b)))
        }, 3, 4))

    fmt.Println("1+2+...+5 =", sum(1, 2, 3, 4, 5))

    a, b := 3, 4
    a, b = swap(a, b)
    fmt.Println("a, b after swap is:", a, b)
}

Summary

  • Function is defined with the keyword func.
  • When defining a function, the function name is before and the return type is after.
  • A function can have multiple return values.
  • The return value can specify a name (for very simple functions only).
  • The function can be used as an argument.
  • There are no default and optional parameters for functions in Go language, and functions are overloaded

Topics: Go Programming