Implicit Interface Implementation
In Go, interfaces are implemented implicitly. A type satisfies an interface by simply implementing its methods; there is no 'implements' keyword. This decouples the definition of the interface from…
Open snippet →Read these Intermediate Go snippets line by line — each one comes with a written breakdown of what the code does and why.
In Go, interfaces are implemented implicitly. A type satisfies an interface by simply implementing its methods; there is no 'implements' keyword. This decouples the definition of the interface from…
Open snippet →Functions in Go are first-class citizens. You can define custom function types, which is useful for implementing patterns like Strategy or Middleware, allowing behavior to be passed as arguments.
Open snippet →Go 1.13+ introduced error wrapping using the %w verb in fmt.Errorf. This allows you to add context to an error while still being able to check for the original sentinel error using errors.Is.
Open snippet →The 'select' statement lets a goroutine wait on multiple communication operations. Using a 'default' case allows for non-blocking sends and receives, executing immediately if no channel is ready.
Open snippet →Go uses struct embedding to achieve composition. When a type is embedded without a field name, its methods and fields are 'promoted' to the outer struct, allowing them to be accessed directly.
Open snippet →The recover built-in function allows a program to regain control of a panicking goroutine. It must always be called within a deferred function to effectively catch the panic before the program exits.
Open snippet →When using append, Go may need to reallocate the underlying array if the capacity is exceeded. By providing a capacity hint in make(), you reduce CPU overhead and memory fragmentation.
Open snippet →A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for, each worker calls Done when finished, and Wait blocks until all…
Open snippet →Table-driven testing is a Go idiom where test cases are defined as a slice of anonymous structs. This makes it easy to add new scenarios and ensures consistent testing logic across multiple inputs.
Open snippet →The context package is essential for managing the lifecycle and cancellation of concurrent processes. WithTimeout creates a derived context that automatically cancels itself after a specified durat…
Open snippet →