Answer the question
In order to leave comments, you need to log in
Please explain defer in golang?
There is a code (fully working). Interested in closing the file
package main
import "os"
func main() {
var text string = "\nmy test string"
// откроем файл
fo, err := os.OpenFile("testfile22.txt", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {panic(err)}
// закроем файл
defer fo.Close()
// проверим на ошибку при закрытии файла
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// запись
if _, err := fo.WriteString(text); err != nil {
panic(err)
}
}
Answer the question
In order to leave comments, you need to log in
https://blog.golang.org/defer-panic-and-recover
describes quite clearly what's what.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question