Hacker News new | ask | show | jobs
by rovolo 2316 days ago
RE (2): Defer. The diagram has an extra box in the control flow which is unnecessary. You can label the big boxes from top to bottom like so: A E B <unnecessary> D C.

A good use case for understanding the control flow of 'defer' is when cleaning up resources.

    mutex.lock();
    defer { mutex.unlock(); }

    val f = File.open(filename);
    defer { f.close(); }

    // write to file
It's a nice construct because it keeps construction and destruction close together instead of far apart

    mutex.lock();
    val f = File.open(filename);

    // write to file

    f.close();
    mutex.unlock();