Go Tips for Newbie Gophers
Mar 15, 2014This 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 ./…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.
go test ./…
Have an io.Writer that writes to an in-memory data structure:
b := &bytes.Buffer{}Have an io.Reader read from a string (useful when you want to use a string as the input data for something):
thing.WriteTo(b)
r := strings.NewReader(myString)Copy data from a reader to a writer:
thing.ReadFrom(r)
io.Copy(toWriter, fromReader)Timeout waiting on a channel:
select {Convert a slice of bytes to a string:
case val := <- ch
// use val
case <-time.After(time.Second*5)
}
var b []byte = getData()Passing a nil pointer into an interface does not result in a nil interface:
s := string(b)
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.