{"id":168638,"date":"2020-01-09T09:09:23","date_gmt":"2020-01-09T01:09:23","guid":{"rendered":"https:\/\/lrxjmw.cn\/?p=168638"},"modified":"2019-12-30T11:12:00","modified_gmt":"2019-12-30T03:12:00","slug":"linux-go-defer","status":"publish","type":"post","link":"https:\/\/lrxjmw.cn\/linux-go-defer.html","title":{"rendered":"\u6559\u4f60\u4e00\u4e2ago\u4e2ddefer\u7684\u9690\u85cf\u529f\u80fd"},"content":{"rendered":"
\u5bfc\u8bfb<\/td>\n | \u8fd9\u7bc7\u6587\u7ae0\u4e3b\u8981\u4ecb\u7ecd\u4e86\u6d45\u8c08go\u4e2ddefer\u7684\u4e00\u4e2a\u9690\u85cf\u529f\u80fd\uff0c\u6587\u4e2d\u901a\u8fc7\u793a\u4f8b\u4ee3\u7801\u4ecb\u7ecd\u7684\u975e\u5e38\u8be6\u7ec6\uff0c\u5bf9\u5927\u5bb6\u7684\u5b66\u4e60\u6216\u8005\u5de5\u4f5c\u5177\u6709\u4e00\u5b9a\u7684\u53c2\u8003\u5b66\u4e60\u4ef7\u503c\uff0c\u9700\u8981\u7684\u670b\u53cb\u4eec\u4e0b\u9762\u968f\u7740\u5c0f\u7f16\u6765\u4e00\u8d77\u5b66\u4e60\u5b66\u4e60\u5427<\/strong><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n \u5728\u5f00\u59cb\u4f7f\u7528Go\u8fdb\u884c\u7f16\u7801\u65f6\uff0cDefer\u662f\u8981\u5173\u6ce8\u7684\u4e00\u4e2a\u5f88\u91cd\u8981\u7684\u7279\u6027\u3002\u5b83\u975e\u5e38\u7b80\u5355\uff1a\u5728\u4efb\u4f55\u51fd\u6570\u4e2d\uff0c\u7ed9\u5176\u4ed6\u51fd\u6570\u7684\u8c03\u7528\u52a0\u4e0a\u524d\u7f00 defer\u4ee5\u786e\u4fdd\u8be5\u51fd\u6570\u5728\u5916\u90e8\u51fd\u6570\u9000\u51fa\u4e4b\u524d\u7acb\u5373\u6267\u884c\uff0c\u5373\u4f7f\u5916\u90e8\u51fd\u6570\u51fa\u73b0\u5f02\u5e38\u88ab\u4e2d\u65ad\uff0c\u8be5\u5ef6\u8fdf\u51fd\u6570\u4e5f\u5c06\u8fd0\u884c\u3002<\/p>\n \u4f46\u662f\uff0c\u4f60\u8fd8\u53ef\u4ee5\u4f7f\u7528defer\u5728\u4efb\u4f55\u51fd\u6570\u5f00\u59cb\u540e\u548c\u7ed3\u675f\u524d\u6267\u884c\u914d\u5bf9\u7684\u4ee3\u7801\u3002\u8fd9\u4e2a\u9690\u85cf\u7684\u529f\u80fd\u5728\u7f51\u4e0a\u7684\u6559\u7a0b\u548c\u4e66\u7c4d\u4e2d\u5f88\u5c11\u63d0\u5230\u3002\u8981\u4f7f\u7528\u6b64\u529f\u80fd\uff0c\u9700\u8981\u521b\u5efa\u4e00\u4e2a\u51fd\u6570\u5e76\u4f7f\u5b83\u672c\u8eab\u8fd4\u56de\u53e6\u4e00\u4e2a\u51fd\u6570\uff0c\u8fd4\u56de\u7684\u51fd\u6570\u5c06\u4f5c\u4e3a\u771f\u6b63\u7684\u5ef6\u8fdf\u51fd\u6570\u3002\u5728 defer \u8bed\u53e5\u8c03\u7528\u7236\u51fd\u6570\u540e\u5728\u5176\u4e0a\u6dfb\u52a0\u989d\u5916\u7684\u62ec\u53f7\u6765\u5ef6\u8fdf\u6267\u884c\u8fd4\u56de\u7684\u5b50\u51fd\u6570\u5982\u4e0b\u6240\u793a\uff1a<\/p>\n func main() {\r\n defer greet()() \r\n fmt.Println(\"Some code here...\")\r\n}\r\n \r\nfunc greet() func() {\r\n fmt.Println(\"Hello!\")\r\n return func() { fmt.Println(\"Bye!\") } \/\/ this will be deferred\r\n}<\/pre>\n |