Skip to content
  • Yorick Peterse's avatar
    Add support for deferred execution of blocks · 703ff73c
    Yorick Peterse authored
    The method `std::process.defer` can be used to schedule a block for
    execution when the calling scope returns, even when a panic is
    triggered. Such blocks are useful when cleaning up resources, such as
    files and sockets.
    
    Most languages use finalisers for this, but finalisers are difficult to
    implement in Inko. The garbage collector has to be able to deal with
    objects that are resurrected, and somehow be able to schedule finalisers
    for execution. Usage wise, finalisers are also more limited as they are
    defined when defining an object, not when using it. This means you
    (typically) can't create ad-hoc finalisers.
    
    The use of deferred blocks allows us to work around these restrictions
    and implementation difficulties, and the idea is inspired by Go. One
    downside is that directly using `std::process.defer` can lead to rather
    verbose code, but more high-level abstractions can be added on top
    easily.
    
    The order in which blocks are executed is currently not officially
    specified, and thus should not be relied upon. Currently the order will
    be First In Last Out (FILO), but this may change at any given point in
    time.
    
    Using `std::process.defer` is very straightforward. For example, to
    close a file once we are done with it, you'd write something along the
    lines of the following:
    
        import std::process
        import std::fs::file
    
        let readme = try! file.read_only('README.md')
    
        process.defer {
          readme.close
        }
    
        try! readme.read_string
    703ff73c