This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging

1. Return value of the function

When a function is called, it returns the result of execution at the point where it was called. This is called the return value of the function and the call needs to receive the result with a variable

1. A function can return multiple values

  • A function can have no return value, one return value, or multiple return values
pageage main
import "fmt"
func local(s, y string)(string, string) {
    return y, x
}
func main() {
    a, b := local("xiaohe", "afei")
    fmt.Println(a, b)
} // afei, xiaohe

func product(A, B int) (add int, multiplied int) {
    add = A + B
    multiplied = A + B
    return
}  // nil
Copy the code

2. Blank identifier

_ is the blank identifier in GO. It can replace any value of any type

For example, the rectPoints function returns an area and a perimeter. If we just want the area and not the perimeter, we can use a blank identifier

package main
import "fmt"
func rectPoints(length, width float64) (float64, float64) {
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}

func main() {
    area, _ := rectPoints(10, 5)
    fmt.Printf("area is %f", area)
} // 50
Copy the code

2. The scope of variables in the function

Scope: The scope within which variables can be used

A local variable

A variable defined inside a function is called a local variable

Where a variable is defined, it can only be used within that range, and beyond that range, we think the variable is destroyed, right

// Define function [testScope], Func testScope(args int) {args = 100 fmt.println (args)} var args int testScope(args) fmT.println (args)} // 100 // nilCopy the code

The global variable

A variable defined outside a function is called a global variable

All functions are available and the data is shared

Recursive function

What is a recursive function that is executed within the body of a loop and must have a condition that terminates the current loop when certain conditions are met, otherwise the loop is infinite

For example, the Fibonacci sequence

/* Position value 1 1 2 1 3 2 4 3.. . n func(n-1) + func(n-2) */Copy the code

Pass a position and return the value of the current position

- 1. Define functions [fibonaci] realization func fibonaci (index int64) int64 {if index = = 1 | | index = = {return 1} else {2 return fibonaci(index-1) + fibonaci(index-2) } } - 2. Println(fibonaci(2))Copy the code

defer

What is the delay

The defer statement is used to execute a function call before the function is returned

Delay function

You can add multiple defer statements to the function. As the function executes to the end, these defer statements are executed in reverse order, and the function returns as the end. In particular, when you open some resources, you need to return ahead of the error, before returning you need to close the corresponding resources, otherwise it is easy to cause resource leakage and other problems

  • If there are many calls to defer, then defer is takenLast in, first outmodel
  • When leaving the method, execute (error is also executed)
func reader() bool { file.Open("file") defer file.close() if failureX { return false } if failureY { return false } Return true} file.close()Copy the code

Example:

Package main import "FMT" func main() {a := 1 b := 2 defer fmt.println (b) fmt.println (a)} // Result // 1 // 2Copy the code

Example:

package main
import "fmt"

func finished() {
    fmt.Println("Finished finding largest")
}

func largest(nums []int) {
    defer finished()
    fmt.Println("started finding largest")
    max := nums[0]
    for _, v := range nums {
        if v > max {
            max = v
        }
    }
    fmt.Println("largest number in", nums, "is", max)
}

func main() {
    nums := []int{1, 2, 3, 4, 5}
    largest(nums)
}

// Started finding largest
// largest number in [1 2 3 4 5] is 5
// Finished finding largest
Copy the code

Delay method

Delays are not limited to functions. It is also perfectly legal to defer a method call.

package main
import "fmt"

type person struct {
    firstName string
    lastName string
}

func (p person) fullName() {
    fmt.Printf("%s %s", p.firstName.p.lastName)
}

func main() {
    p := person {
        firstName: "xiaohe",
        lastName: "afei"
    }
    defer p.fullName()
    fmt.Printnf("Welcome")
}

// Welcome xiaohe afei
Copy the code

Delay parameter

Arguments to the delay function are executed when the delay statement is executed, not when the function call is remembered

package main import "fmt" func printA(a int) { fmt.Println("value of a in deferred function", A)} func main() {a := 5 defer printA(a) a = 10 fmt.Println("value of a befored function call", a)} // // Value of a befored function call 10 // Value of a in deferred function 5Copy the code

Delay of stack

When a function has multiple delayed calls, they are added to a stack and executed in a last in first out (LIFO) order

package main
import "fmt"

func main() {
    name := "afei"
    fmt.Printf("name string %s\n", string(name))
    fmt.Printf('reversed string:")
    for _, v := range []rune(name) {
        defer fmt.Printf("%c", v)
    }
}
// name string: afei
// reversed string: AFEI
Copy the code

Pay attention to as:

  • When the statement in the enclosing function finishes executing normally, the enclosing function will not finish executing until all of its delayed functions have finished executing.
  • When a return statement in a enclosing function is executed, the enclosing function does not return until all of its delayed functions have been executed.
  • When the code in the enclosing function causes a run panic, the run time panic is only truly extended to the calling function after all the delayed functions in it have been executed.