Skip to content

Learning Go – Miniblog #5 – Compiler Problem

January 11, 2013

This carries on from here.

I was happily proceeding with code to list the contents of text files in a directory, when I came up against a problem  The program will read a  list of path names from the command line, list those which are files, iterate over those which are directories, and report errors for those that simply don’t exist. to do that, I need to know if something is a directory or not. To do this, I came up with this function:

func isdir( fname string ) bool {
    info,err := os.Stat( fname )
    if err != nil {
        return false
    } else {
        return info.IsDir()
    }
}

OK, this doesn’t handle the "does not exist" case, but I figured I’d get to that later. Anyway, when compiling this code I got this error:

.\direct.go:36: function ends without a return statement

Now, I stared at that code long and hard, and could not see any way that the function could fall through to the end without executing a return statement. Unfortunately, it seems the Go compiler cannot see that. Some googling came up with this post from Rob Pike (one of the designers of Go) in the http://groups.google.com/group/golang-nuts groups.

The compilers require either a return or a panic to be lexically last in a function with a result. This rule is easier than requiring full flow control analysis to determine whether a function reaches the end without returning (which is very hard in general), and simpler than rules to enumerate easy cases such as this one. Also, being purely lexical, the error cannot arise spontaneously due to changes in values such as constants used in control structures inside the function.

So, it’s a feature. Apparently, the Go compiler is incapable of doing what all modern compilers  for other languages can do, and it’s up to the programmer to work around it. This isn’t difficult to do:

func isdir( fname string ) bool {
    info,err := os.Stat( fname )
    if err != nil {
        return false
    }
    return info.IsDir()
}

does the job, but I really don’t think that I should have to write code like this – and the problem becomes even more ugly if you are using a long if/else ladder or a switch statement. Ho-hum; I wonder what other surprises lie in store…

 

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: