diff --git a/.github/ISSUE_TEMPLATE/community_mistake.md b/.github/ISSUE_TEMPLATE/community_mistake.md new file mode 100644 index 0000000..5510486 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/community_mistake.md @@ -0,0 +1,14 @@ +--- +name: Community mistake +about: Propose a new community mistake +title: '' +labels: community mistake +--- + +**Describe the mistake** + +Describe the mistake and include a context if required. + +**Solution** + +One or multiple solutions to avoid the mistake. diff --git a/.github/ISSUE_TEMPLATE/erratum.md b/.github/ISSUE_TEMPLATE/erratum.md new file mode 100644 index 0000000..7cd8d34 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/erratum.md @@ -0,0 +1,10 @@ +--- +name: Erratum +about: Suggest a book correction +title: '' +labels: erratum +--- + +**Describe the book error** + +Describe a factual error in the book and suggest a correction. diff --git a/README.md b/README.md index d3a240f..83a97e4 100644 --- a/README.md +++ b/README.md @@ -1,158 +1,152 @@ # 📖 100 Go Mistakes and How to Avoid Them -Source code of [100 Go Mistakes and How to Avoid Them](https://www.manning.com/books/100-go-mistakes-and-how-to-avoid-them), edited by Manning (Oct. 2022). +Source code and community space of [100 Go Mistakes and How to Avoid Them](https://www.manning.com/books/100-go-mistakes-and-how-to-avoid-them) (Manning, Oct. 2022). -![](cover.png) +**Note:** If you're struggling to afford the book, please DM me [@teivah](https://twitter.com/teivah). -* [Table of Contents](#table-of-contents) -* [100 Go Mistakes Map](#100-go-mistakes-map) -* [References](#references) -* [Author](#author) -* [Quotes](#quotes) +![](inside-cover.jpg) -## Table of Contents +## Go Mistakes -### Chapter 1 - Introduction +### Code and Project Organization -### Chapter 2 - Code and Project Organization - -#### #1: Unintended variable shadowing +#### Unintended variable shadowing (#1) Avoiding shadowed variables can help prevent mistakes like referencing the wrong variable or confusing readers. -#### #2: Unnecessary nested code +#### Unnecessary nested code (#2) Avoiding nested levels and keeping the happy path aligned on the left makes building a mental code model easier. -#### #3: Misusing init functions +#### Misusing init functions (#3) When initializing variables, remember that init functions have limited error handling and make state handling and testing more complex. In most cases, initializations should be handled as specific functions. -#### #4: Overusing getters and setters +#### Overusing getters and setters (#4) Forcing the use of getters and setters isn’t idiomatic in Go. Being pragmatic and finding the right balance between efficiency and blindly following certain idioms should be the way to go. -#### #5: Interface pollution +#### Interface pollution (#5) Abstractions should be discovered, not created. To prevent unnecessary complexity, create an interface when you need it and not when you foresee needing it, or if you can at least prove the abstraction to be a valid one. -#### #6: Interface on the producer side +#### Interface on the producer side (#6) Keeping interfaces on the client side avoids unnecessary abstractions. -#### #7: Returning interfaces +#### Returning interfaces (#7) To prevent being restricted in terms of flexibility, a function shouldn’t return interfaces but concrete implementations in most cases. Conversely, a function should accept interfaces whenever possible. -#### #8: `any` says nothing +#### `any` says nothing (#8) Only use `any` if you need to accept or return any possible type, such as `json.Marshal`. Otherwise, `any` doesn’t provide meaningful information and can lead to compile-time issues by allowing a caller to call methods with any data type. -#### #9: [Being confused about when to use generics](https://teivah.medium.com/when-to-use-generics-in-go-36d49c1aeda) +#### [Being confused about when to use generics](https://teivah.medium.com/when-to-use-generics-in-go-36d49c1aeda) (#9) Relying on generics and type parameters can prevent writing boilerplate code to factor out elements or behaviors. However, do not use type parameters prematurely, but only when you see a concrete need for them. Otherwise, they introduce unnecessary abstractions and complexity. -#### #10: Not being aware of the possible problems with type embedding +#### Not being aware of the possible problems with type embedding (#10) Using type embedding can also help avoid boilerplate code; however, ensure that doing so doesn’t lead to visibility issues where some fields should have remained hidden. -#### #11: Not using the functional options pattern +#### Not using the functional options pattern (#11) To handle options conveniently and in an API-friendly manner, use the functional options pattern. -#### #12: Project misorganization (project structure and package organization) +#### Project misorganization (project structure and package organization) (#12) Following a layout such as project-layout can be a good way to start structuring Go projects, especially if you are looking for existing conventions to standardize a new project. -#### #13: Creating utility packages +#### Creating utility packages (#13) Naming is a critical piece of application design. Creating packages such as `common`, `util`, and `shared` doesn’t bring much value for the reader. Refactor such packages into meaningful and specific package names. -#### #14: Ignoring package name collisions +#### Ignoring package name collisions (#14) To avoid naming collisions between variables and packages, leading to confusion or perhaps even bugs, use unique names for each one. If this isn’t feasible, use an import alias to change the qualifier to differentiate the package name from the variable name, or think of a better name. -#### #15: Missing code documentation +#### Missing code documentation (#15) To help clients and maintainers understand your code’s purpose, document exported elements. -#### #16: Not using linters +#### Not using linters (#16) To improve code quality and consistency, use linters and formatters. -### Chapter 3 - Data Types +### Data Types -#### #17: Creating confusion with octal literals +#### Creating confusion with octal literals (#17) When reading existing code, bear in mind that integer literals starting with 0 are octal numbers. Also, to improve readability, make octal integers explicit by prefixing them with `0o`. -#### #18: Neglecting integer overflows +#### Neglecting integer overflows (#18) Because integer overflows and underflows are handled silently in Go, you can implement your own functions to catch them. -#### #19: Not understanding floating-points +#### Not understanding floating-points (#19) Making floating-point comparisons within a given delta can ensure that your code is portable. When performing addition or subtraction, group the operations with a similar order of magnitude to favor accuracy. Also, perform multiplication and division before addition and subtraction. -#### #20: Not understanding slice length and capacity +#### Not understanding slice length and capacity (#20) Understanding the difference between slice length and capacity should be part of a Go developer’s core knowledge. The slice length is the number of available elements in the slice, whereas the slice capacity is the number of elements in the backing array. -#### #21: Inefficient slice initialization +#### Inefficient slice initialization (#21) When creating a slice, initialize it with a given length or capacity if its length is already known. This reduces the number of allocations and improves performance. The same logic goes for maps, and you need to initialize their size. -#### #22: Being confused about nil vs. empty slice +#### Being confused about nil vs. empty slice (#22) To prevent common confusions such as when using the `encoding/json` or the `reflect` package, you need to understand the difference between nil and empty slices. Both are zero-length, zero-capacity slices, but only a nil slice doesn’t require allocation. -#### #23: Not properly checking if a slice is empty +#### Not properly checking if a slice is empty (#23) To check if a slice doesn’t contain any element, check its length. This check works regardless of whether the slice is `nil` or empty. The same goes for maps. To design unambiguous APIs, you shouldn’t distinguish between nil and empty slices. -#### #24: Not making slice copies correctly +#### Not making slice copies correctly (#24) To copy one slice to another using the `copy` built-in function, remember that the number of copied elements corresponds to the minimum between the two slice’s lengths. -#### #25: Unexpected side effects using slice append +#### Unexpected side effects using slice append (#25) Using copy or the full slice expression is a way to prevent `append` from creating conflicts if two different functions use slices backed by the same array. However, only a slice copy prevents memory leaks if you want to shrink a large slice. -#### #26: Slice and memory leaks +#### Slice and memory leaks (#26) Working with a slice of pointers or structs with pointer fields, you can avoid memory leaks by marking as nil the elements excluded by a slicing operation. -#### #27: Inefficient map initialization +#### Inefficient map initialization (#27) See [#22](#21-inefficient-slice-initialization). -#### #28: Map and memory leaks +#### Map and memory leaks (#28) A map can always grow in memory, but it never shrinks. Hence, if it leads to some memory issues, you can try different options, such as forcing Go to recreate the map or using pointers. -#### #29: Comparing values incorrectly +#### Comparing values incorrectly (#29) To compare types in Go, you can use the == and != operators if two types are comparable: Booleans, numerals, strings, pointers, channels, and structs are composed entirely of comparable types. Otherwise, you can either use `reflect.DeepEqual` and pay the price of reflection or use custom implementations and libraries. -### Chapter 4 - Control Structures +### Control Structures -#### #30: Ignoring that elements are copied in `range` loops +#### Ignoring that elements are copied in `range` loops (#30) The value element in a `range` loop is a copy. Therefore, to mutate a struct, for example, access it via its index or via a classic `for` loop (unless the element or the field you want to modify is a pointer). -#### #31: Ignoring how arguments are evaluated in `range` loops (channels and arrays) +#### Ignoring how arguments are evaluated in `range` loops (channels and arrays) (#31) Understanding that the expression passed to the `range` operator is evaluated only once before the beginning of the loop can help you avoid common mistakes such as inefficient assignment in channel or slice iteration. -#### #32: Ignoring the impacts of using pointer elements in `range` loops +#### Ignoring the impacts of using pointer elements in `range` loops (#32) Using a local variable or accessing an element using an index, you can prevent mistakes while copying pointers inside a loop. -#### #33: Making wrong assumptions during map iterations (ordering and map insert during iteration) +#### Making wrong assumptions during map iterations (ordering and map insert during iteration) (#33) To ensure predictable outputs when using maps, remember that a map data structure: * Doesn’t order the data by keys @@ -160,197 +154,197 @@ To ensure predictable outputs when using maps, remember that a map data structur * Doesn’t have a deterministic iteration order * Doesn’t guarantee that an element added during an iteration will be produced during this iteration -#### #34: Ignoring how the `break` statement work +#### Ignoring how the `break` statement work (#34) Using `break` or `continue` with a label enforces breaking a specific statement. This can be helpful with `switch` or `select` statements inside loops. -#### #35: Using `defer` inside a loop +#### Using `defer` inside a loop (#35) Extracting loop logic inside a function leads to executing a `defer` statement at the end of each iteration. -### Chapter 5 - Strings +### Strings -#### #36: Not understanding the concept of rune +#### Not understanding the concept of rune (#36) Understanding that a rune corresponds to the concept of a Unicode code point and that it can be composed of multiple bytes should be part of the Go developer’s core knowledge to work accurately with strings. -#### #37: Inaccurate string iteration +#### Inaccurate string iteration (#37) Iterating on a string with the `range` operator iterates on the runes with the index corresponding to the starting index of the rune’s byte sequence. To access a specific rune index (such as the third rune), convert the string into a `[]rune`. -#### #38: Misusing trim functions +#### Misusing trim functions (#38) `strings.TrimRight`/`strings.TrimLeft` removes all the trailing/leading runes contained in a given set, whereas `strings.TrimSuffix`/`strings.TrimPrefix` returns a string without a provided suffix/prefix. -#### #39: Under-optimized strings concatenation +#### Under-optimized strings concatenation (#39) Concatenating a list of strings should be done with `strings.Builder` to prevent allocating a new string during each iteration. -#### #40: Useless string conversions +#### Useless string conversions (#40) Remembering that the `bytes` package offers the same operations as the `strings` package can help avoid extra byte/string conversions. -#### #41: Substring and memory leaks +#### Substring and memory leaks (#41) Using copies instead of substrings can prevent memory leaks, as the string returned by a substring operation will be backed by the same byte array. -### Chapter 6 - Functions and Methods +### Functions and Methods -#### #42: Not knowing which type of receiver to use +#### Not knowing which type of receiver to use (#42) The decision whether to use a value or a pointer receiver should be made based on factors such as the type, whether it has to be mutated, whether it contains a field that can’t be copied, and how large the object is. When in doubt, use a pointer receiver. -#### #43: Never using named result parameters +#### Never using named result parameters (#43) Using named result parameters can be an efficient way to improve the readability of a function/method, especially if multiple result parameters have the same type. In some cases, this approach can also be convenient because named result parameters are initialized to their zero value. But be cautious about potential side effects. -#### #44: Unintended side effects with named result parameters +#### Unintended side effects with named result parameters (#44) See [#43](#43-never-using-named-result-parameters). -#### #45: Returning a nil receiver +#### Returning a nil receiver (#45) When returning an interface, be cautious about returning not a nil pointer but an explicit nil value. Otherwise, unintended consequences may result because the caller will receive a non-nil value. -#### #46: Using a filename as a function input +#### Using a filename as a function input (#46) Designing functions to receive `io.Reader` types instead of filenames improves the reusability of a function and makes testing easier. -#### #47: Ignoring how `defer` arguments and receivers are evaluated (argument evaluation, pointer, and value receivers) +#### Ignoring how `defer` arguments and receivers are evaluated (argument evaluation, pointer, and value receivers) (#47) Passing a pointer to a `defer` function and wrapping a call inside a closure are two possible solutions to overcome the immediate evaluation of arguments and receivers. -### Chapter 7 - Error Management +### Error Management -#### #48: Panicking +#### Panicking (#48) Using `panic` is an option to deal with errors in Go. However, it should only be used sparingly in unrecoverable conditions: for example, to signal a programmer error or when you fail to load a mandatory dependency. -#### #49: Ignoring when to wrap an error +#### Ignoring when to wrap an error (#49) Wrapping an error allows you to mark an error and/or provide additional context. However, error wrapping creates potential coupling as it makes the source error available for the caller. If you want to prevent that, don’t use error wrapping. -#### #50: Comparing an error type inaccurately +#### Comparing an error type inaccurately (#50) If you use Go 1.13 error wrapping with the `%w` directive and `fmt.Errorf`, comparing an error against a type or a value has to be done using `errors.As` or `errors.Is`, respectively. Otherwise, if the returned error you want to check is wrapped, it will fail the checks. -#### #51: Comparing an error value inaccurately +#### Comparing an error value inaccurately (#51) See [#50](#50-comparing-an-error-type-inaccurately). To convey an expected error, use error sentinels (error values). An unexpected error should be a specific error type. -#### #52: Handling an error twice +#### Handling an error twice (#52) In most situations, an error should be handled only once. Logging an error is handling an error. Therefore, you have to choose between logging or returning an error. In many cases, error wrapping is the solution as it allows you to provide additional context to an error and return the source error. -#### #53: Not handling an error +#### Not handling an error (#53) Ignoring an error, whether during a function call or in a `defer` function, should be done explicitly using the blank identifier. Otherwise, future readers may be confused about whether it was intentional or a miss. -#### #54: Not handling `defer` errors +#### Not handling `defer` errors (#54) In many cases, you shouldn’t ignore an error returned by a `defer` function. Either handle it directly or propagate it to the caller, depending on the context. If you want to ignore it, use the blank identifier. -### Chapter 8 - Concurrency: Foundations +### Concurrency: Foundations -#### #55: Mixing up concurrency and parallelism +#### Mixing up concurrency and parallelism (#55) Understanding the fundamental differences between concurrency and parallelism is a cornerstone of the Go developer’s knowledge. Concurrency is about structure, whereas parallelism is about execution. -#### #56: Thinking concurrency is always faster +#### Thinking concurrency is always faster (#56) To be a proficient developer, you must acknowledge that concurrency isn’t always faster. Solutions involving parallelization of minimal workloads may not necessarily be faster than a sequential implementation. Benchmarking sequential versus concurrent solutions should be the way to validate assumptions. -#### #57: Being puzzled about when to use channels or mutexes +#### Being puzzled about when to use channels or mutexes (#57) Being aware of goroutine interactions can also be helpful when deciding between channels and mutexes. In general, parallel goroutines require synchronization and hence mutexes. Conversely, concurrent goroutines generally require coordination and orchestration and hence channels. -#### #58: Not understanding race problems (data races vs. race conditions and the Go memory model) +#### Not understanding race problems (data races vs. race conditions and the Go memory model) (#58) Being proficient in concurrency also means understanding that data races and race conditions are different concepts. Data races occur when multiple goroutines simultaneously access the same memory location and at least one of them is writing. Meanwhile, being data-race-free doesn’t necessarily mean deterministic execution. When a behavior depends on the sequence or the timing of events that can’t be controlled, this is a race condition. Understanding the Go memory model and the underlying guarantees in terms of ordering and synchronization is essential to prevent possible data races and/or race conditions. -#### #59: Not understanding the concurrency impacts of a workload type +#### Not understanding the concurrency impacts of a workload type (#59) When creating a certain number of goroutines, consider the workload type. Creating CPU-bound goroutines means bounding this number close to the `GOMAXPROCS` variable (based by default on the number of CPU cores on the host). Creating I/O-bound goroutines depends on other factors, such as the external system. -#### #60: Misunderstanding Go contexts +#### Misunderstanding Go contexts (#60) Go contexts are also one of the cornerstones of concurrency in Go. A context allows you to carry a deadline, a cancellation signal, and/or a list of keys-values. -### Chapter 9 - Concurrency: Practice +### Concurrency: Practice -#### #61: Propagating an inappropriate context +#### Propagating an inappropriate context (#61) Understanding the conditions when a context can be canceled should matter when propagating it: for example, an HTTP handler canceling the context when the response has been sent. -#### #62: Starting a goroutine without knowing when to stop it +#### Starting a goroutine without knowing when to stop it (#62) Avoiding leaks means being mindful that whenever a goroutine is started, you should have a plan to stop it eventually. -#### #63: Not being careful with goroutines and loop variables +#### Not being careful with goroutines and loop variables (#63) To avoid bugs with goroutines and loop variables, create local variables or call functions instead of closures. -#### #64: Expecting a deterministic behavior using select and channels +#### Expecting a deterministic behavior using select and channels (#64) Understanding that `select` with multiple channels chooses the case randomly if multiple options are possible prevents making wrong assumptions that can lead to subtle concurrency bugs. -#### #65: Not using notification channels +#### Not using notification channels (#65) Send notifications using a `chan struct{}` type. -#### #66: Not using nil channels +#### Not using nil channels (#66) Using nil channels should be part of your concurrency toolset because it allows you to _remove_ cases from `select` statements, for example. -#### #67: Being puzzled about channel size +#### Being puzzled about channel size (#67) Carefully decide on the right channel type to use, given a problem. Only unbuffered channels provide strong synchronization guarantees. You should have a good reason to specify a channel size other than one for buffered channels. -#### #68: Forgetting about possible side effects with string formatting (etcd data race example and deadlock) +#### Forgetting about possible side effects with string formatting (etcd data race example and deadlock) (#68) Being aware that string formatting may lead to calling existing functions means watching out for possible deadlocks and other data races. -#### #69: Creating data races with append +#### Creating data races with append (#69) Calling `append` isn’t always data-race-free; hence, it shouldn’t be used concurrently on a shared slice. -#### #70: Using mutexes inaccurately with slices and maps +#### Using mutexes inaccurately with slices and maps (#70) Remembering that slices and maps are pointers can prevent common data races. -#### #71: Misusing `sync.WaitGroup` +#### Misusing `sync.WaitGroup` (#71) To accurately use `sync.WaitGroup`, call the `Add` method before spinning up goroutines. -#### #72: Forgetting about `sync.Cond` +#### Forgetting about `sync.Cond` (#72) You can send repeated notifications to multiple goroutines with `sync.Cond`. -#### #73: Not using `errgroup` +#### Not using `errgroup` (#73) You can synchronize a group of goroutines and handle errors and contexts with the `errgroup` package. -#### #74: Copying a `sync` type +#### Copying a `sync` type (#74) `sync` types shouldn’t be copied. -### Chapter 10 - Standard Library +### Standard Library -#### #75: Providing a wrong time duration +#### Providing a wrong time duration (#75) Remain cautious with functions accepting a `time.Duration`. Even though passing an integer is allowed, strive to use the time API to prevent any possible confusion. -#### #76: `time.After` and memory leaks +#### `time.After` and memory leaks (#76) Avoiding calls to `time.After` in repeated functions (such as loops or HTTP handlers) can avoid peak memory consumption. The resources created by `time.After` are released only when the timer expires. -#### #77: JSON handling common mistakes +#### JSON handling common mistakes (#77) * Unexpected behavior because of type embedding @@ -364,7 +358,7 @@ Avoiding calls to `time.After` in repeated functions (such as loops or HTTP hand To avoid wrong assumptions when you provide a map while unmarshaling JSON data, remember that numerics are converted to `float64` by default. -#### #78: Common SQL mistakes +#### Common SQL mistakes (#78) * Forgetting that `sql.Open` doesn't necessarily establish connections to a database @@ -386,53 +380,53 @@ Avoiding calls to `time.After` in repeated functions (such as loops or HTTP hand Call the `Err` method of `sql.Rows` after row iterations to ensure that you haven’t missed an error while preparing the next row. -#### #79: Not closing transient resources (HTTP body, `sql.Rows`, and `os.File`) +#### Not closing transient resources (HTTP body, `sql.Rows`, and `os.File`) (#79) Eventually close all structs implementing `io.Closer` to avoid possible leaks. -#### #80: Forgetting the return statement after replying to an HTTP request +#### Forgetting the return statement after replying to an HTTP request (#80) To avoid unexpected behaviors in HTTP handler implementations, make sure you don’t miss the `return` statement if you want a handler to stop after `http.Error`. -#### #81: Using the default HTTP client and server +#### Using the default HTTP client and server (#81) For production-grade applications, don’t use the default HTTP client and server implementations. These implementations are missing timeouts and behaviors that should be mandatory in production. -### Chapter 11 - Testing +### Testing -#### #82: Not categorizing tests (build tags, environment variables, and short mode) +#### Not categorizing tests (build tags, environment variables, and short mode) (#82) Categorizing tests using build flags, environment variables, or short mode makes the testing process more efficient. You can create test categories using build flags or environment variables (for example, unit versus integration tests) and differentiate short from long-running tests to decide which kinds of tests to execute. -#### #83: Not enabling the race flag +#### Not enabling the race flag (#83) Enabling the `-race` flag is highly recommended when writing concurrent applications. Doing so allows you to catch potential data races that can lead to software bugs. -#### #84: Not using test execution modes (parallel and shuffle) +#### Not using test execution modes (parallel and shuffle) (#84) Using the `-parallel` flag is an efficient way to speed up tests, especially long-running ones. Use the `-shuffle` flag to help ensure that a test suite doesn’t rely on wrong assumptions that could hide bugs. -#### #85: Not using table-driven tests +#### Not using table-driven tests (#85) Table-driven tests are an efficient way to group a set of similar tests to prevent code duplication and make future updates easier to handle. -#### #86: Sleeping in unit tests +#### Sleeping in unit tests (#86) Avoid sleeps using synchronization to make a test less flaky and more robust. If synchronization isn’t possible, consider a retry approach. -#### #87: Not dealing with the time API efficiently +#### Not dealing with the time API efficiently (#87) Understanding how to deal with functions using the time API is another way to make a test less flaky. You can use standard techniques such as handling the time as part of a hidden dependency or asking clients to provide it. -#### #88: Not using testing utility packages (`httptest` and `iotest`) +#### Not using testing utility packages (`httptest` and `iotest`) (#88) The `httptest` package is helpful for dealing with HTTP applications. It provides a set of utilities to test both clients and servers. The `iotest` package helps write io.Reader and test that an application is tolerant to errors. -#### #89: Writing inaccurate benchmarks +#### Writing inaccurate benchmarks (#89) * Not resetting or pausing the timer Use time methods to preserve the accuracy of a benchmark. @@ -451,7 +445,7 @@ The `iotest` package helps write io.Reader and test that an application is toler To prevent the observer effect, force a benchmark to re-create the data used by a CPU-bound function. -#### #90: Not exploring all the Go testing features +#### Not exploring all the Go testing features (#90) * Code coverage Use code coverage with the `-coverprofile` flag to quickly see which part of the code needs more attention. @@ -468,9 +462,10 @@ The `iotest` package helps write io.Reader and test that an application is toler You can use setup and teardown functions to configure a complex environment, such as in the case of integration tests. -### Chapter 12 - Optimizations +### Optimizations + +#### Not understanding CPU caches (#91) -#### #91: Not understanding CPU caches * CPU architecture Understanding how to use CPU caches is important for optimizing CPU-bound applications because the L1 cache is about 50 to 100 times faster than the main memory. @@ -489,78 +484,44 @@ The `iotest` package helps write io.Reader and test that an application is toler To avoid a critical stride, hence utilizing only a tiny portion of the cache, be aware that caches are partitioned. -#### #92: Writing concurrent code that leads to false sharing +#### Writing concurrent code that leads to false sharing (#92) Knowing that lower levels of CPU caches aren’t shared across all the cores helps avoid performance-degrading patterns such as false sharing while writing concurrency code. Sharing memory is an illusion. -#### #93: Not taking into account instruction-level parallelism +#### Not taking into account instruction-level parallelism (#93) Use instruction-level parallelism (ILP) to optimize specific parts of your code to allow a CPU to execute as many parallel instructions as possible. Identifying data hazards is one of the main steps. -#### #94: Not being aware of data alignment +#### Not being aware of data alignment (#94) You can avoid common mistakes by remembering that in Go, basic types are aligned with their own size. For example, keep in mind that reorganizing the fields of a struct by size in descending order can lead to more compact structs (less memory allocation and potentially a better spatial locality). -#### #95: Not understanding stack vs. heap +#### Not understanding stack vs. heap (#95) Understanding the fundamental differences between heap and stack should also be part of your core knowledge when optimizing a Go application. Stack allocations are almost free, whereas heap allocations are slower and rely on the GC to clean the memory. -#### #96: Not knowing how to reduce allocations (API change, compiler optimizations, and `sync.Pool`) +#### Not knowing how to reduce allocations (API change, compiler optimizations, and `sync.Pool`) (#96) Reducing allocations is also an essential aspect of optimizing a Go application. This can be done in different ways, such as designing the API carefully to prevent sharing up, understanding the common Go compiler optimizations, and using `sync.Pool`. -#### #97: Not relying on inlining +#### Not relying on inlining (#97) Use the fast-path inlining technique to efficiently reduce the amortized time to call a function. -#### #98: Not using Go diagnostics tooling (profiling [enabling pprof, CPU, heap, goroutines, block, and mutex profiling] and execution tracer) +#### #98: Not using Go diagnostics tooling (profiling [enabling pprof, CPU, heap, goroutines, block, and mutex profiling] and execution traceRely on profiling and the execution tracer to understand how an application performs and the parts to optimize. #())) -Rely on profiling and the execution tracer to understand how an application performs and the parts to optimize. - -#### #99: Not understanding how the GC works +#### Not understanding how the GC works (#99) Understanding how to tune the GC can lead to multiple benefits such as handling sudden load increases more efficiently. -#### #100: Not understanding the impacts of running Go in Docker and Kubernetes +#### Not understanding the impacts of running Go in Docker and Kubernetes (#100) To help avoid CPU throttling when deployed in Docker and Kubernetes, keep in mind that Go isn’t CFS-aware. -## 100 Go Mistakes Map - -![](inside-cover.jpg) - -## References +## Resources * How to make mistakes in Go (Go Time - episode #190) * [Episode](https://changelog.com/gotime/190) * [Spotify](https://open.spotify.com/episode/0K1DImrxHCy6E7zVY4AxMZ?si=akroInsPQ1mM5B5V2tHLUw&dl_branch=1) * 8LU - 100% Test Coverage: [YouTube](https://youtu.be/V3FBDav6wgQ?t=1210) - -## Author - -Teiva Harsanyi is a senior software engineer at Docker. He worked in various domains, including insurance, transportation, and safety-critical industries like air traffic management. He is passionate about Go and how to design and implement reliable applications. - -**Note:** If you're struggling to afford the book, please DM me [@teivah](https://twitter.com/teivah). - -## Quotes - -> "This should be the required reading for all Golang developers before they touch code in Production... It's the Golang equivalent of the legendary 'Effective Java' by Joshua Bloch." - -– Neeraj Shah - -> "This unique book teaches you good habits by helping you identify bad ones. Harsanyi's writing style is engaging, the examples relevant, and his insights useful. I thought it was a great read, and I think you will too." - -– Thad Meyer - -> "Learning from mistakes is proven as one of the best ways to learn a subject. This book helps you do just that by demonstrating the most common mistakes people make coming to Go, why most people make them and the proper way to solve the problems." - -– Ryan Huber - -> "This book explains many subtleties of the Go programming language that may cause errors and provides the reader with advice on how to deal with these situations. The precise explanations and real world examples make it a great addition for those learning Go programming language or looking to advance their mastery of the language." - -– Borko Djurkovic - -> "Not having this will be the 101st mistake a Go programmer could make." - -– Anupam Sengupta diff --git a/book.md b/book.md new file mode 100644 index 0000000..f5e8397 --- /dev/null +++ b/book.md @@ -0,0 +1,71 @@ +# 100 Go Mistakes and How to Avoid Them + +Spot errors in your Go code you didn’t even know you were making and boost your productivity by avoiding common mistakes and pitfalls. + +![](cover.png) + +_100 Go Mistakes and How to Avoid Them_ shows you how to: + +* Dodge the most common mistakes made by Go developers +* Structure and organize your Go application +* Handle data and control structures efficiently +* Deal with errors in an idiomatic manner +* Improve your concurrency skills +* Optimize your code +* Make your application production-ready and improve testing quality + + +_100 Go Mistakes and How to Avoid Them_ puts a spotlight on common errors in Go code you might not even know you’re making. You’ll explore key areas of the language such as concurrency, testing, data structures, and more—and learn how to avoid and fix mistakes in your own projects. As you go, you’ll navigate the tricky bits of handling JSON data and HTTP services, discover best practices for Go code organization, and learn how to use slices efficiently. + +## About the Technology + +Understanding mistakes is the best way to improve the quality of your code. This unique book examines 100 bugs and inefficiencies common to Go applications, along with tips and techniques to avoid making them in your own projects. + +## About the Book + +_100 Go Mistakes and How to Avoid Them_ shows you how to replace common programming problems in Go with idiomatic, expressive code. In it, you’ll explore dozens of interesting examples and case studies as you learn to spot mistakes that might appear in your own applications. Expert author Teiva Harsanyi organizes the error avoidance techniques into convenient categories, ranging from types and strings to concurrency and testing. + +## Table of Contents + +1. Go: Simple to learn but hard to master +2. Code and project organization +3. Data types +4. Control structures +5. Strings +6. Functions and methods +7. Error management +8. Concurrency: Foundations +9. Concurrency: Practice +10. Standard library +11. Testing +12. Optimizations + +## About the Reader + +For developers proficient with Go programming and syntax. + +## About the Author + +Teiva Harsanyi is a senior software engineer at Docker. He worked in various domains, including insurance, transportation, and safety-critical industries like air traffic management. He is passionate about Go and how to design and implement reliable applications. + +## Quotes + +> "This should be the required reading for all Golang developers before they touch code in Production... It's the Golang equivalent of the legendary 'Effective Java' by Joshua Bloch." + +– Neeraj Shah + +> "This unique book teaches you good habits by helping you identify bad ones. Harsanyi's writing style is engaging, the examples relevant, and his insights useful. I thought it was a great read, and I think you will too." + +– Thad Meyer + +> "Learning from mistakes is proven as one of the best ways to learn a subject. This book helps you do just that by demonstrating the most common mistakes people make coming to Go, why most people make them and the proper way to solve the problems." + +– Ryan Huber + +> "This book explains many subtleties of the Go programming language that may cause errors and provides the reader with advice on how to deal with these situations. The precise explanations and real world examples make it a great addition for those learning Go programming language or looking to advance their mastery of the language." + +– Borko Djurkovic + +> "Not having this will be the 101st mistake a Go programmer could make." + +– Anupam Sengupta