This is a creation in Article, where the information may have evolved or changed.
Return and defer order:
Return first, then run defer, you can modify the return value:
package mainimport ( "fmt")func main() { fmt.Println(test())}//返回值为2funcint) { deferfunc() { result++ }() return 1//return函数先返回 result被赋值为1 然后再result++}
Here's a good point, because the return value is named, so we return 1 is the result assignment to 1.
In addition, if the return value is anonymous, but you return a named variable, whether the return value will be modified.
package mainimport ( "fmt")func main() { fmt.Println(test())}//输出为0funcint { varint deferfunc() { a++ }() return a }
Prove that the return value can not be modified, specifically with the scope should have a relationship, there is time to delve into. Of course, if you return a return value of a to a named result and then modify result, the return value can be modified.
The use that has been encountered in the project
In the processing of panic, the panic error message is used as the return value, and the simplified code is as follows:
package mainimport ( "FMT" "Runtime/debug" ) func Main () {FMT. PRINTLN (Test ())}func Test () (err error) {defer func () {if e: = recover (); E! = nil {err = FMT. Errorf ( "%s \ n panic:\n%s" , E, Debug. Stack ()) //print E (Panic of exception information replenishment results) and strongly recommends that the print stack information be used to locate the error. }} () var a int a = 1 /a return nil }
The returned results are as follows:
RuntimeError:Integer divide by zeroPanic:Goroutine1[Running]:Runtime/debug.Stack(0xc042031d88,0x49d220,0xc042004060)C:/go/src/runtime/debug/stack.go: -+0x80MAIN.TEST.FUNC1 (0xc042031ea8)C:/users/colinhome/documents/github/test/src/structindex/base64.go: -+0x6aPanic0x49d220,0xc042004060)C:/go/src/runtime/panic.go:458+0x251Main.test (0x0,0x0)C:/users/colinhome/documents/github/test/src/structindex/base64.go: ++0x80Main.main ()C:/users/colinhome/documents/github/test/src/structindex/base64.go:9+0x3b
Can be positioned to a specific number of rows. Easy to Debug.