Skip to content

Learning Go – Miniblog #6 – Defer

January 12, 2013

This carries on from here.

Well, I finally got my directory listing to work. The code looks like this:

func listdir( dirname string ) error { dirf,err := os.Open( dirname ) if err != nil { return err } dir,err := dirf.Readdir(-1) if err != nil { return err } for _,val := range( dir ) { if ( ! val.IsDir() ) {

// use my own listfile function listfile( val.Name() ) } } dirf.Close() return nil }

I call os.Open() to open the directory as I would a file (you can tell the the Go creators are UNIX people) and then call Readdir() (should be ReadDir, surely?) on the directory/file to get a slice containing the directory information. Then I iterate over this information, and for things that are not directories, I list them using my own listfile() function. Lastly, I close the directory/file.

It’s that last bit that gave me pause. Coming from C++, I’m used to not having to worry about doing things like call Close() – I expect the file object (or a smart pointer) to do that for me by the wonder that is RAII. Go apparently doesn’t work like that, but it does give you the ability to specify functions that will be called when your own function exits,  whatever the reason and route of exit.  To use it, you simply say something like:

func listdir( dirname string ) error {
    dirf,err := os.Open( dirname )
    if err != nil {
        return err
    }
    defer dirf.Close()
    // remainder as before
    // but with final call to Close() removed

Now, when the function exits, Close() will be called on the dirf file pointer.

To me, this seems a less general and less elegant solution than RAII, but maybe I will learn to love it. Now I need to get a directory listing of .CSV files only…

Advertisements

From → golang

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: