copy
and recover
functions. On the other hand, we have learned that the result values of a deferred function call must be discarded, so the calls to many built-in functions can't be deferred.
append
function may needed to be deferred sometimes. For this case, we can defer a call to an anonymous function which wraps the append
call.
package main
import "fmt"
func main() {
s := []string{"a", "b", "c", "d"}
defer fmt.Println(s) // [a x y d]
// defer append(s[:1], "x", "y") // error
defer func() {
_ = append(s[:1], "x", "y")
}()
}
false
.
package main
import "fmt"
func main() {
var f = func () {
fmt.Println(false)
}
defer f()
f = func () {
fmt.Println(true)
}
}
package main
import "fmt"
func main() {
defer fmt.Println("reachable 1")
var f func() // f is nil by default
defer f() // panic here
// The following lines are also reachable.
fmt.Println("reachable 2")
f = func() {} // useless to avoid panicking
}
1342
.
package main
type T int
func (t T) M(n int) T {
print(n)
return t
}
func main() {
var t T
// "t.M(1)" is the receiver argument of the method
// call ".M(2)", so it is evaluated when the
// ".M(2)" call is pushed into defer-call stack.
defer t.M(1).M(2)
t.M(3).M(4)
}
import "os"
func withoutDefers(filepath string, head, body []byte) error {
f, err := os.Open(filepath)
if err != nil {
return err
}
_, err = f.Seek(16, 0)
if err != nil {
f.Close()
return err
}
_, err = f.Write(head)
if err != nil {
f.Close()
return err
}
_, err = f.Write(body)
if err != nil {
f.Close()
return err
}
err = f.Sync()
f.Close()
return err
}
func withDefers(filepath string, head, body []byte) error {
f, err := os.Open(filepath)
if err != nil {
return err
}
defer f.Close()
_, err = f.Seek(16, 0)
if err != nil {
return err
}
_, err = f.Write(head)
if err != nil {
return err
}
_, err = f.Write(body)
if err != nil {
return err
}
return f.Sync()
}
f.Close()
calls in the function without deferred calls that it has a higher possibility to miss one of them.
doSomething
calls panic in the following example, the function f2
will exit without unlocking the Mutex
value. So the function f1
is less bug prone.
var m sync.Mutex
func f1() {
m.Lock()
defer m.Unlock()
doSomething()
}
func f2() {
m.Lock()
doSomething()
m.Unlock()
}
func writeManyFiles(files []File) error {
for _, file := range files {
f, err := os.Open(file.path)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(file.content)
if err != nil {
return err
}
err = f.Sync()
if err != nil {
return err
}
}
return nil
}
func writeManyFiles(files []File) error {
for _, file := range files {
if err := func() error {
f, err := os.Open(file.path)
if err != nil {
return err
}
// The close method will be called at
// the end of the current loop step.
defer f.Close()
_, err = f.WriteString(file.content)
if err != nil {
return err
}
return f.Sync()
}(); err != nil {
return err
}
}
return nil
}
The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.
reflect
standard package.sync
standard package.sync/atomic
standard package.