From f49590aa5e8079e84ddf31c510cff9c2620761ee Mon Sep 17 00:00:00 2001 From: Arseny Balobanov Date: Thu, 25 Feb 2021 16:08:25 +0300 Subject: [PATCH] [lectures/02-interfaces] Add defer and recover slides. --- lectures/02-interfaces/copyfile/copy.go | 23 ++++++++ lectures/02-interfaces/copyfile2/copy.go | 22 ++++++++ lectures/02-interfaces/lecture.slide | 71 ++++++++++++++++++++++++ 3 files changed, 116 insertions(+) create mode 100644 lectures/02-interfaces/copyfile/copy.go create mode 100644 lectures/02-interfaces/copyfile2/copy.go diff --git a/lectures/02-interfaces/copyfile/copy.go b/lectures/02-interfaces/copyfile/copy.go new file mode 100644 index 0000000..e6a064b --- /dev/null +++ b/lectures/02-interfaces/copyfile/copy.go @@ -0,0 +1,23 @@ +package copyfile + +import ( + "io" + "os" +) + +func CopyFile(dstName, srcName string) (written int64, err error) { + src, err := os.Open(srcName) + if err != nil { + return + } + + dst, err := os.Create(dstName) + if err != nil { + return + } + + written, err = io.Copy(dst, src) + dst.Close() + src.Close() + return +} diff --git a/lectures/02-interfaces/copyfile2/copy.go b/lectures/02-interfaces/copyfile2/copy.go new file mode 100644 index 0000000..384f000 --- /dev/null +++ b/lectures/02-interfaces/copyfile2/copy.go @@ -0,0 +1,22 @@ +package copyfile2 + +import ( + "io" + "os" +) + +func CopyFile(dstName, srcName string) (written int64, err error) { + src, err := os.Open(srcName) + if err != nil { + return + } + defer src.Close() + + dst, err := os.Create(dstName) + if err != nil { + return + } + defer dst.Close() + + return io.Copy(dst, src) +} diff --git a/lectures/02-interfaces/lecture.slide b/lectures/02-interfaces/lecture.slide index a760fa9..3b99f4f 100644 --- a/lectures/02-interfaces/lecture.slide +++ b/lectures/02-interfaces/lecture.slide @@ -411,6 +411,52 @@ Check type x.elements = nil } +* defer + +.play copyfile/copy.go /func/,/^}/ + +* defer + +.play copyfile2/copy.go /func/,/^}/ + +* defer + + func a() { + i := 0 + defer fmt.Println(i) + i++ + return + } + +Output: + + 0 + +* defer + + func b() { + for i := 0; i < 4; i++ { + defer fmt.Print(i) + } + } + +Output: + + 3210 + +* defer + + func c() (i int) { + defer func() { i++ }() + return 1 + } + + fmt.Println(c()) + +Output: + + 2 + * defer func main() { @@ -443,6 +489,31 @@ Output: // ...parser... } + +* recover + + func main() { + defer func() { + recover() + fmt.Println("Checkpoint 1") + panic(1) + }() + defer func() { + recover() + fmt.Println("Checkpoint 2") + panic(2) + }() + panic(999) + } + +Output: + + Checkpoint 2 + Checkpoint 1 + panic: 999 [recovered] + panic: 2 [recovered] + panic: 1 + * errors type error interface {