Go Notes

These are things I want to remember in Go

Format Strings

  • %+v is introduced by Dave Cheney’s errors package. A common use case:
if err != nil {
    // Add a stack
    err = errors.WithStack(err)
    log.Fatalf("%+v\n", err)
}

NOTE: I’m not sure this is the same as panic(err). Something to check

  • %#v is equivalent to Python’s repr function - it formats the data structure like it would look if you typed it in code.
s = NewMyStruct(param1, param2)
fmt.Printf("%#v\n", s)

Using logrus

logrus is a pretty nice logging library for go. It focuses on logging key-value pairs along with a message. This is super useful for me because 90% of the time I just want to see those values anyway.

NOTE: I need to test this code

package mypackage

import (
	log "github.com/sirupsen/logrus"
)

func myFunc() {
	log.WithFields(log.Fields{
		"sqlStatement": statement,
		"sqlArgs":      args,
	}).Debug("Oops")
}
package main

import (
	log "github.com/sirupsen/logrus"
)

func init() {
	log.SetLevel(log.DebugLevel)
}

func main() {
	myFunc()
}

Iterator type things in Go TODO

  • PageDataIterator
  • Scanner
  • How to loop with it and for

Documentation

This section of Google’s API design book is also really relevant to Go development. I’ve pasted it below. I want to start using it for my function documentation:

Checklist for all descriptions

Make sure each description is brief but complete and can be understood by users who don’t have additional information about the API. In most cases, there’s more to say than just restating the obvious; for example, the description of the series.insert method shouldn’t just say “Inserts a series.” — while your naming should be informative, most readers are reading your descriptions because they want more information than the names themselves provide. If you’re not sure what else to say in a description, try answering all of the following questions that are relevant:

  • What is it?
  • What does it do if it succeeds? What does it do if it fails? What can cause it to fail, and how?
  • Is it idempotent?
  • What are the units? (Examples: meters, degrees, pixels.)
  • What range of values does it accept? Is the range inclusive or exclusive?
  • What are the side effects?
  • How do you use it?
  • What are common errors that may break it?
  • Is it always present? (For example: “Container for voting information. Present only when voting information is recorded.”)
  • Does it have a default setting?