Go Tips for Newbie Gophers

This is just a collection of tips that would have saved me a lot of time if I had known about them when I was a newbie:

Build or test everything under the current directory and subdirectories:

go build ./…
go test ./…
Technically, both commands take a pattern to match the name of one or more packages, and the … specifier is a wildcard, so you could do …/foo/… to match all packages under GOPATH with foo in their path. 

Have an io.Writer that writes to an in-memory data structure:

b := &bytes.Buffer{}
thing.WriteTo(b)
Have an io.Reader read from a string (useful when you want to use a string as the input data for something):
r := strings.NewReader(myString)
thing.ReadFrom(r)
Copy data from a reader to a writer:

io.Copy(toWriter, fromReader)
Timeout waiting on a channel:

select {
   case val := <- ch
       // use val
   case <-time.After(time.Second*5)
}
Convert a slice of bytes to a string:
var b []byte = getData()
s := string(b)
Passing a nil pointer into an interface does not result in a nil interface:
func isNil(i interface{}) bool {
    return i == nil
}
var f *foo = nil
fmt.Println(isNil(f))  // prints false
The only way to get a nil interface is to pass the keyword nil:
var f *foo = nil
if f == nil {
    fmt.Println(isNil(nil))  // prints true
}
How to remember where the arrow goes for channels:

The arrow points in the direction of data flow, either into or out of the channel, and always points left.

The above is generalizable to anything where you have a source and destination, or reading and writing, or assigning.

Data is taken from the right and assigned to the left, just as it is with a := b.  So, like io.Copy, you know that the reader (source) is on the right, the writer (destination) is on the left:  io.Copy(dest, src).

If you ever think “man, someone should have made a helper function to do this!”, chances are they have, and it’s in the std lib somewhere.

w