3

Learning Go – Miniblog #6 – Defer | Late Developer

 2 years ago
source link: https://latedev.wordpress.com/2013/01/12/learning-go-miniblog-6-defer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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
Report this ad

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK