Watching: Writing Beautiful Packages in Go
Author(s): Mat Ryer
Finished: 12:25
Packages have some internal and external fields, structs, functions, etc. Package main is only for commands.
Think of packages like creating an API
Useful questions to ask before writing a package spec
Who is the user?
What are they trying to do?
Why are they doing it?
Why are they using my package?
Is my package part of a bigger system?
Make sure the number of exported "items" is as small as possible.
Core package functions should have broader types as arguments. e.g. io.Writer
instead of os.File
.
Try to implement single method interfaces, where there's just a single function to call. Here's a good and famous example.
single-method interface
type Handler interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
// function adapter
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
func (h handlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return h(w, r)
}
cmd
- commands only
pkg
- packages only
testdata
- data for tests
docs
- extra docs?
Use multiple .go files Keep types close to where they're used Organize by responsibility (user type goes into user.go) Optimize for the godoc and provide examples