Irbisa · Cheatsheet
Standard Library in Practice
io and bufio, encoding/json, time, strconv, regexp, embed
Which struct fields does
encoding/jsonencode, and what can ajson:"..."tag change about them?// wrong: nothing is exported: Marshal returns "{}" and a nil errortype order struct { id int64 total int64 `json:"total"` // a tag on an unexported field does nothing status string}…How do you read a file in Go (
os.ReadFile,os.Openwithbufio, orio.Copy), and when do you pick each?// small file: one call, memory = file sizefunc loadJSON(path string, v any) error { b, err := os.ReadFile(path) if err != nil { return err }…What does a
bufio.Writerdo with the bytes you write into it, and why must you callFlushbefore closing the file?type Row struct { ID int64 Name string} func export(path string, rows []Row) (err error) {…What does this print, and what is the right way to turn a number into a string and back?
func main() { n := 65 a := string(n) b := strconv.Itoa(n) c, err := strconv.Atoi("65 ") fmt.Printf("%q %q %d %v\n", a, b, c, err)}Why does Go format dates with the layout
2006-01-02 15:04:05instead ofYYYY-MM-DD?const layout = "2006-01-02 15:04:05" // an example, not a pattern func main() { t := time.Date(2024, 3, 5, 9, 7, 0, 0, time.UTC) // wrong: Format never errors: unknown letters are copied through as themselves…What does
//go:embeddo, which variable types can it fill, and why does it fix a file path that works from the project directory but fails on the server?//go:embed version.txtvar version string // one file as a string //go:embed templates/*.htmlvar tmplFS embed.FS…When do you use
crypto/randinstead ofmath/rand, and what changed withmath/rand/v2and seeding?import ( crand "crypto/rand" "math/rand/v2" "time")…How would you gzip, hash and count a file while uploading it (in one pass, without holding it in memory) using only the standard library?
// One pass: gzip to dst, sha256 of the plaintext, count of compressed bytes.func upload(dst io.Writer, name string) (sum []byte, n int64, err error) { f, err := os.Open(name) if err != nil { return nil, 0, err }…What is the difference between
bufio.Scannerandbufio.Reader, and why does a Scanner stop on some files withtoken too long?func importLines(r io.Reader, handle func([]byte) error) error { s := bufio.NewScanner(r) s.Buffer(make([]byte, 0, 64*1024), 4*1024*1024) // 64 KB start, 4 MB cap for s.Scan() { // s.Bytes() aliases the scanner's buffer: copy it if you keep it if err := handle(s.Bytes()); err != nil {…What does
omitemptytreat as empty, and why is a zerotime.Timestill encoded?type Profile struct { Tags []string `json:"tags"` // nil -> null, []string{} -> [] Nick string `json:"nick,omitempty"` // "" -> key absent Score int `json:"score,omitempty"` // 0 -> absent: "score 0" cannot be sent Seen *int `json:"seen,omitempty"` // nil -> absent, &0 -> "seen":0 Created time.Time `json:"created,omitempty"` // wrong: a struct is never "empty"…A webhook relay decodes payloads into
map[string]anyand re-encodes them. What does this print, and why do large ids come out changed?const raw = `{"order_id":12345678901234567}` func main() { var m map[string]any json.Unmarshal([]byte(raw), &m) fmt.Printf("%T\n", m["order_id"]) out, _ := json.Marshal(m) fmt.Println(string(out))}Config key
max_connsbecamemaxConnectionsand the service booted silently with a zero pool. Whichencoding/jsonrules allowed it, and how do you make it fail?type Config struct { Addr string `json:"addr"` MaxConns int `json:"max_conns"`} func load(r io.Reader) (Config, error) {…Find the bug: some orders get a coupon the customer never entered.
type Order struct { ID string `json:"id"` Coupon string `json:"coupon"`} func parseOrders(lines [][]byte) ([]Order, error) { var out []Order var o Order for _, line := range lines { if err := json.Unmarshal(line, &o); err != nil { return nil, err } out = append(out, o) } return out, nil}This
MarshalJSONshould encodeEvent.Atas a plain date. Why does the first call crash the whole process, and what is the fix?type Event struct { Name string `json:"name"` At time.Time `json:"at"`} func (e Event) MarshalJSON() ([]byte, error) { type payload = Event // "a copy of Event without the method" return json.Marshal(struct { payload At string `json:"at"` }{payload(e), e.At.Format(time.DateOnly)})}What does the experimental
encoding/json/v2from Go 1.25 change compared withencoding/json, and when do teams still pickeasyjsonorsonic?What is reflection in Go, where does the standard library rely on it, and what does it cost you?
type Config struct { Host string `env:"APP_HOST"` Port int `env:"APP_PORT"`} // Fills string and int fields from the env vars named in `env` tags.…Why is Go's
regexpguaranteed to run in linear time, and what can it not do?How do you load configuration in a Go service with only the standard library (defaults, environment variables, flags), and where does validation belong?
type Config struct { Addr string DatabaseURL string Timeout time.Duration}…How do you write a TCP server with
net.ListenandAccept, and what must you add for deadlines and graceful shutdown?type Server struct { ln net.Listener wg sync.WaitGroup conns sync.Map // live connections done chan struct{} // closed by Shutdown: the quit signal}…NTP steps the clock back 400 ms:
time.Since(start)stays right,end.UnixNano() - start.UnixNano()goes negative. What doestime.Timecarry that explains it?How do you ingest a 40 GB NDJSON file whose
datashape depends on each line'stype, in constant memory and decoding each line into Go values once?type Envelope struct { Type string `json:"type"` Data json.RawMessage `json:"data"` // raw bytes until Type is known} type Push struct{ Ref string `json:"ref"` }…What can
unsafe.Pointerdo that ordinary Go cannot, and why is a zero-copy[]byte-to-stringconversion withunsafe.Stringa bug if the bytes change?func main() { buf := []byte("alice") // wrong: zero-copy, so name shares buf's bytes name := unsafe.String(unsafe.SliceData(buf), len(buf)) seen := map[string]bool{name: true}…Find the bug:
checksumof agzip.Readerusually does not matchsha256sumof the unpacked file, yet it returns no error.// called as: zr, _ := gzip.NewReader(f); sum, err := checksum(zr)func checksum(r io.Reader) ([]byte, error) { h := sha256.New() buf := make([]byte, 32*1024) for { n, err := r.Read(buf) if err == io.EOF { break } if err != nil { return nil, err } h.Write(buf[:n]) } return h.Sum(nil), nil}