After spending every free minute to Go I’m starting to get a feel for the language. Every one has to start somewhere, so I decided to “port” Unix utils to Go. I’m starting with cat, and thanks to the Go tutorial this is the result.

package main

// An implementation of Unix cat in Go

import (
    "os";
    "fmt";
    "flag";
)

func cat(filename string) bool {
    const NBUF = 512;
    var buf [NBUF]byte;
    if f, e := os.Open(filename, os.O_RDONLY, 0); e != nil {
	    fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
		    filename, e.String());
	    return true;
    } else {
	    for {
		    switch nr, _ := f.Read(&buf); true {
		    case nr < 0:
			    os.Exit(1)
		    case nr == 0:	// EOF
			    return true
		    case nr > 0:
			    if nw, ew := os.Stdout.Write(buf[0:nr]); nw != nr {
				    fmt.Fprintf(os.Stderr,
					    "cat: error writing from %s: %s\n",
					    filename, ew.String());
				    return false;
			    }
		    }
	    }
    }
    return true;
}

func main() {
    flag.Parse();	// implement -n TODO
    if flag.NArg() == 0 {
	    cat("/dev/stdin")
    }
    for i := 0; i < flag.NArg(); i++ {
	    if !cat(flag.Arg(i)) {
		    os.Exit(1)
	    }
    }
}

In something like 50 lines you have a cat program. I’m really starting to like Go. Next up: extra features and a grep command.