Source code of the 100 Go Mistakes book

Overview

100 Go Mistakes and How to Avoid Them

Source code of 100 Go Mistakes and How to Avoid Them.

Table of Contents

Chapter 1 - Introduction

Chapter 2 - Code and Project Organization

  • 1 - Unintended variable shadowing
  • 2 - Writing nested code
  • 3 - Misusing init functions
  • 4 - Always using getters and setters
  • 5 - Interface pollution
  • 6 - Interface on the producer side
  • 7 - Returning interfaces
  • 8 - any says nothing
  • 9 - Being confused about when to use generics
  • 10 - Not being aware of the possible problems with type embedding
  • 11 - Not using the functional options pattern
  • 12 - Project misorganization (project structure and package organization)
  • 13 - Creating utility packages
  • 14 - Ignoring package name collisions
  • 15 - Missing code documentation
  • 16 - Not using linters

Chapter 3 - Data Types

  • 17 - Creating confusion with octal literals
  • 18 - Neglecting integer overflows
  • 19 - Not understanding floating-points
  • 20 - Not understanding slice length and capacity
  • 21 - Inefficient slice initialization
  • 22 - Being confused about nil vs. empty slice
  • 23 - Not properly checking if a slice is empty
  • 24 - Not making slice copy correctly
  • 25 - Unexpected side-effects using slice append
  • 26 - Slice and memory leaks
  • 27 - Inefficient map initialization
  • 28 - Map and memory leaks
  • 29 - Comparing values incorrectly

Chapter 4 - Control Structures

  • 30 - Ignoring that elements are copied in range loops
  • 31 - Ignoring how arguments are evaluated in range loops (channels and arrays)
  • 32 - Ignoring the impacts of using pointer elements in range loops
  • 33 - Making wrong assumptions during map iterations (ordering and map insert during iteration)
  • 34 - Ignoring how the break statement work
  • 35 - Using defer inside a loop

Chapter 5 - Strings

  • 36 - Not understanding the concept of rune
  • 37 - Inaccurate string iteration
  • 38 - Misusing trim functions
  • 39 - Under-optimized strings concatenation
  • 40 - Useless string conversion
  • 41 - Substring and memory leaks

Chapter 6 - Functions and Methods

  • 42 - Not knowing which type of receiver to use
  • 43 - Never using named result parameters
  • 44 - Unintended side-effects with named result parameters
  • 45 - Returning a nil receiver
  • 46 - Using a filename as a function input
  • 47 - Ignoring how defer arguments and receivers are evaluated

Chapter 7 - Error Management

  • 48 - Panicking
  • 49 - Ignoring when to wrap an error
  • 50 - Comparing an error type inaccurately
  • 51 - Comparing an error value inaccurately
  • 52 - Handling an error twice
  • 53 - Not handling an error
  • 54 - Not handling defer errors

Chapter 8 - Concurrency: Foundations

  • 55 - Mixing concurrency and parallelism
  • 56 - Concurrency isn't always faster
  • 57 - Being puzzled about when to use channels or mutexes
  • 58 - Not understanding race problems (data races vs. race conditions and Go memory model)
  • 59 - Not understanding the concurrency impacts of a workload type
  • 60 - Misunderstanding Go contexts

Chapter 9 - Concurrency: Practice

  • 61 - Propagating an inappropriate context
  • 62 - Starting a goroutine without knowing when to stop it
  • 63 - Not being careful with goroutines and loop variables
  • 64 - Expecting a deterministic behavior using select and channels
  • 65 - Not using notification channels
  • 66 - Not using nil channels
  • 67 - Being puzzled about a channel size
  • 68 - Forgetting about possible side-effects with string formatting (etcd and dead-lock)
  • 69 - Creating data races with append
  • 70 - Using mutexes inaccurately with slices and maps
  • 71 - Misusing sync.WaitGroup
  • 72 - Forgetting about sync.Cond
  • 73 - Not using errgroup
  • 74 - Copying a sync type

Chapter 10 - Standard Library

  • 75 - Providing a wrong time duration
  • 76 - time.After and memory leak
  • 77 - JSON handling common mistakes
    • Unexpected behavior because of type embedding
    • JSON and monotonic clock
    • Map of any
  • 78 - SQL common mistakes
    • Forgetting that sql.Open doesn't necessarily establish connections to a DB
    • Forgetting about connections pooling
    • Not using prepared statements
    • Mishandling null values
    • Not handling rows iteration errors
  • 79 - Not closing transient resources (HTTP body, sql.Rows, and os.File)
  • 80 - Forgetting the return statement after replying to an HTTP request
  • 81 - Using the default HTTP client and server

Chapter 11 - Testing

  • 82 - Not categorizing tests (build tags and short mode)
  • 83 - Not enabling the race flag
  • 84 - Not using test execution modes (parallel and shuffle)
  • 85 - Not using table-driven tests
  • 86 - Sleeping in unit tests
  • 87 - Not dealing with the time API efficiently
  • 88 - Not using testing utility packages (httptest and iotest)
  • 89 - Writing inaccurate benchmarks
    • Not resetting or pausing the timer
    • Making wrong assumptions about micro-benchmarks
    • Not being careful about compiler optimizations
    • Being fooled by the observer effect
  • 90 - Not exploring all the Go testing features
    • Code coverage
    • Testing from a different package
    • Utility functions
    • Setup and teardown

Chapter 12 - Optimizations

  • 91 - Not understanding CPU caches
    • CPU architecture
    • Cache line
    • Slice of structs vs. struct of slices
    • Predictability
    • Cache placement policy
  • 92 - Writing concurrent code leading to false sharing
  • 93 - Not taking into account instruction-level parallelism
  • 94 - Not being aware of data alignment
  • 95 - Not understanding stack vs. heap
  • 96 - Not knowing how to reduce allocations
    • API change
    • Compiler optimizations
    • sync.Pool
  • 97 - Not relying on inlining
  • 98 - Not using Go diagnostics tooling (profiling and execution tracer)
  • 99 - Not understanding how the GC works
  • 100 - Not understanding the impacts of running Go inside of Docker and Kubernetes
Comments
  • To stop ticker explicitly

    To stop ticker explicitly

    10.1 #75 Providing a wrong time duration should stop ticker, or cause leaks

    ticker := time.NewTicker(1000) // should stop defer
    for {
        select {
        case <-ticker.C:
            // Do something
        }
    }
    
    ticker := time.NewTicker(1000)
    defer ticker.Stop()
    for {
        select {
        case <-ticker.C:
            // Do something
        }
    }
    
    opened by maliyan 1
  • Higher granularity is equivalent to higher rate

    Higher granularity is equivalent to higher rate

    On page 340, section Heap Profiling, high granularity means high rate, but instead it says:

    We can change this rate, but we shouldn't be too granular because the more we decrease the rate, the more effort heap profiling will require to collect data.

    erratum 
    opened by ChristoWolf 1
  • Typo on page 115

    Typo on page 115

    There is a typo in the second to last sentence at the end of mistake 36: Having these concepts in mind is essential because runes ~~as~~ are everywhere in Go. Let's see a concrete application of this knowledge involving a common mistake related to string iteration.

    erratum 
    opened by ChristoWolf 1
  • spell mistake

    spell mistake

    hello, i find one spell mistake in 100-go-mistakes at chapter 9 #63 - Not being careful with goroutines and loop variable.

    in the code, use fmt.Print :

    s := []int{1, 2, 3}
    
    for _, i := range s {
            go func() {
                    fmt.Print(i)
            }()
    }
    

    in the description, use fmt.Println:

    it prints the value of i at the time fmt.Println is executed

    opened by ThomasMing0915 1
  • Swap channel action labels in context-awareness example

    Swap channel action labels in context-awareness example

    Unless I am missing something, the first code example in the "Implementing a function that receives a context" box on page 191 should have the Receive and Send labels switched to refer to the correct channel actions.

    erratum 
    opened by ChristoWolf 0
  • Chinese translation

    Chinese translation

    Gophers in China are also interested in 100-go-mistakes-how-to-avoid-them,but Chinese edition is not available yet. I wish to get your authorization to translate it into Chinese and publish it on Github for free. Thanks a lot @teivah

    opened by JustZyx 4
Owner
Teiva Harsanyi
Software Engineer, Go, Rust, Java | @ReactiveX​/​RxGo | 改善
Teiva Harsanyi
A collection of 100+ popular LeetCode problems solved in Go.

go-leetcode A collection of 100+ popular LeetCode problems that I've solved in Go. Each directory includes a: Description with link to LeetCode proble

Austin Gebauer 1.7k Dec 25, 2022
100 days of Go learning

This repository is a journal of my path to learning GO. By the end of the 100 days, you should be able to follow along by day and learn Go as well.

Cobra 25 Oct 27, 2022
An online book focusing on Go syntax/semantics and runtime related things

Go 101 is a book focusing on Go syntax/semantics and all kinds of runtime related things. It tries to help gophers gain a deep and thorough understanding of Go. This book also collects many details of Go and in Go programming. The book is expected to be helpful for both beginner and experienced Go programmers.

Go101 4.8k Dec 29, 2022
The Little Go Book is a free introduction to Google's Go programming language

The Little Go Book is a free introduction to Google's Go programming language. It's aimed at developers who might not be quite comfortable with the idea of pointers and static typing. It's longer than the other Little books, but hopefully still captures that little feeling.

Dariush Abbasi 13.6k Jan 2, 2023
Lev 1.1k Dec 7, 2021
Coding along the book

Learn Go with Tests Art by Denise Formats Gitbook EPUB or PDF Translations 中文 Português 日本語 한국어 Türkçe Support me I am proud to offer this resource fo

null 0 Oct 30, 2021
📖 A little guide book on Ethereum Development with Go (golang)

?? A little guide book on Ethereum Development with Go (golang)

Miguel Mota 1.5k Dec 29, 2022
Solutions for the exercises available in the book "A Linguagem de Programação Go" by Alan Donovan and Brian Kernighan

Go Exercises This repository contains possible solutions for the exercises available in the book "A Linguagem de Programação Go (in portuguese)" by Al

Paulo Júnior 1 Feb 20, 2022
Book Catalogue, Order RESTful API

Book Catalogue, Order RESTful API try on heroku: https://pacific-island-57943.herokuapp.com Note: '/' endpoint redirect to github repository for docum

Uğur Cibaroğlu 0 Dec 13, 2021
The resource repository of the book "gRPC - Up and Running".

The resource repository of the book "gRPC - Up and Running".

Happy bull 0 Feb 4, 2022
Go from the beginning - A book on Go, contains fundamentals but also recipes

Go from the beginning Welcome to Go from the beginning, a free book containing 25+ lessons that will take you from "zero to hero" in the amazing langu

chris 91 Dec 28, 2022
Markdown version of Reverse Engineering the source code of the BioNTech/Pfizer SARS-CoV-2 Vaccine

The big BNT162b2 archive All vaccine data here is sourced from this World Health Organization document. This describes the RNA contents of the BNT162b

null 163 Dec 2, 2022
An open source, online coding platform that offers code practice and tutoring in 50 different programming languages

Exercism Golang En este repositorio voy a subir los ejercicios de la plataforma

Lucas Frontalini 0 Jan 7, 2022
An open source programming language that makes it easy to build simple

The Go Programming Language Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. Gopher ima

null 0 Oct 15, 2021
An open source recommender system service written in Go

gorse: Go Recommender System Engine Gorse is an open-source recommendation system written in Go. Gorse aims to be a universal open-source recommender

Gorse 6.5k Jan 1, 2023
Assert your Go code is inlined and bounds-check eliminated

gcassert gcassert is a program for making assertions about compiler decisions in Golang programs, via inline comment directives like //gcassert:inline

Jordan Lewis 178 Oct 27, 2022
Go-Notebook is inspired by Jupyter Project (link) in order to document Golang code.

Go-Notebook Go-Notebook is an app that was developed using go-echo-live-view framework, developed also by us. GitHub repository is here. For this proj

Arturo Elias 33 Jan 9, 2023
Example code for my Cadence Intro Workshop

Temporal Intro Workshop This repository contains example code for my Temporal Intro Workshop. Prerequisites Git, Make, etc. Make sure you have the lat

Márk Sági-Kazár 21 Dec 18, 2022
Sample code for my Go Deadlocks talk

Go Deadlocks Talk This is sample code for my Go Deadlocks talk. Simple simple - a super simple deadlock simple2 - the same but with an extra Go deadlo

Nick Craig-Wood 9 Jul 30, 2022