4
4
4utka_pyan2017-06-25 17:14:51
Web development
4utka_pyan, 2017-06-25 17:14:51

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)
    }
}

Correctly, I understand that everything with defer is performed at the very end, i.e. does the WriteString entry occur even when the file is open, despite the fact that the file is closed before that?
Then there are two functions with defer - one for closing, the other for checking for errors when closing. Do they all line up at the end in exactly the order in which they were specified in the code?
What is the point of using defer i.e. why postpone execution until later, because it can be written simply below in the code? In my opinion, if there is more than 1 such thing in the code, there is a real risk of confusing yourself?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Chefranov, 2018-11-28
@Chefranov

It's called Open Graph. You can change/set via Yoast SEO

A
Alexander Aksentiev, 2017-06-25
@4utka_pyan

https://blog.golang.org/defer-panic-and-recover
describes quite clearly what's what.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question