defer 与清理顺序
Coddy 面向 C# 开发者的 Go 课程的第 35 课,共 48 课。
C# 的 using 和 finally 会为 IDisposable 资源提供作用域限定的清理机制。Go 的 defer 作用于函数,而不是最近的词法块,并按后进先出的顺序注册任意调用。参数和闭包的捕获时机有所不同。
defer 会安排在函数返回时调用,包括提前返回的情况。调用按后进先出的顺序执行;到达 defer 时会计算其参数。延迟执行的闭包则可以在执行时读取变量。defer 属于函数作用域,因此在长循环中使用 defer 会将清理推迟到函数结束时。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program { static void Main() {
try{Console.WriteLine("body");}finally{Console.WriteLine("cleanup");}
} }源代码输出:
body
cleanupGo 示例
package main
import ("fmt")
func main(){func(){ defer fmt.Println("last"); defer fmt.Println("first"); fmt.Println("body") }()}
Go 输出:
body
first
last挑战
简单实现 Visit(log *[]string,label string)。先追加 open,再追加 label,并确保 Visit 返回时追加 close。要求的可见行为是确定性的清理;请使用 defer。Solve 用逗号连接日志。
实现已声明的 API,并返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。
你的代码放在 visit.go、exercise.go 中。main.go 包含提供的输入/输出代码,不能编辑。保持一个扁平的 package main,不要添加第二个 main。
亲手试试
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=L(0); before0:=fmt.Sprint(a0)
log:=[]string{"prior"}; Visit(&log,"x");must(strings.Join(log,",")=="prior,open,x,close","cleanup API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Go中的所有课
自己练习: Go 在线编译器