Skip to content

Latest commit

 

History

History
55 lines (42 loc) · 1.4 KB

20200407H.md

File metadata and controls

55 lines (42 loc) · 1.4 KB

April 7, 2020 Hour

Watching: Writing Beautiful Packages in Go

Author(s): Mat Ryer

Finished: 12:25

Before Writing a Package

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?

Exports

Make sure the number of exported "items" is as small as possible.

Types

Core package functions should have broader types as arguments. e.g. io.Writer instead of os.File.

Single Method Interfaces

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)
}

Package Subfolders

cmd - commands only pkg - packages only testdata - data for tests docs - extra docs?

Rakyll Style Guide

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