[lectures/02-interfaces] Add defer and recover slides.
This commit is contained in:
parent
72f428d81c
commit
f49590aa5e
3 changed files with 116 additions and 0 deletions
23
lectures/02-interfaces/copyfile/copy.go
Normal file
23
lectures/02-interfaces/copyfile/copy.go
Normal file
|
@ -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
|
||||
}
|
22
lectures/02-interfaces/copyfile2/copy.go
Normal file
22
lectures/02-interfaces/copyfile2/copy.go
Normal file
|
@ -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)
|
||||
}
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in a new issue