Created
November 10, 2020 06:59
-
-
Save lixianyang/4e09e62b894751122b4eda1488a67aa6 to your computer and use it in GitHub Desktop.
defer 里修改返回值的几种情况
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| func main() { | |
| fmt.Println(f()) | |
| fmt.Println(f1()) | |
| fmt.Println(f2()) | |
| fmt.Println(f3()) | |
| } | |
| func f() (result int) { | |
| defer func() { | |
| result++ | |
| }() | |
| return 0 | |
| } | |
| func f1() (r int) { | |
| t := 5 | |
| defer func() { | |
| t = t + 5 | |
| }() | |
| return t | |
| } | |
| func f2() (r int) { | |
| r = 2 | |
| defer func() { | |
| fmt.Println("input: ", r) | |
| r = r + 5 | |
| }() | |
| return 1 | |
| } | |
| func f3() int { | |
| r := 10 | |
| defer func() { | |
| r++ | |
| }() | |
| return r | |
| } | |
| /* | |
| 1 | |
| 5 | |
| input: 1 | |
| 6 | |
| 10 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment