0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Go · IntermediateSnippet

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 its implementation.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
import "fmt"
type Describer interface {
Describe() string
}
type Product struct {
Name string
Price float64
}
func (p Product) Describe() string {
return fmt.Sprintf("%s costs $%.2f", p.Name, p.Price)
}
func main() {
var d Describer = Product{Name: "Keyboard", Price: 49.99}
fmt.Println(d.Describe())
}
Design PatternsBest Practices
Go · IntermediateSnippet

Custom Function Types for Strategy Pattern

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.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
import "fmt"
type Validator func(string) bool
func IsEmail(s string) bool {
return len(s) > 3 // Simplified logic
}
func ValidateInput(input string, v Validator) {
if v(input) {
fmt.Println("Input is valid")
} else {
fmt.Println("Input is invalid")
}
}
func main() {
ValidateInput("[email protected]", IsEmail)
ValidateInput("", func(s string) bool {
return len(s) > 0
})
}
FunctionsDesign Patterns
Go · IntermediateSnippet

Error Wrapping and Unwrapping

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.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func fetchData() error {
return fmt.Errorf("database error: %w", ErrNotFound)
}
func main() {
err := fetchData()
if err != nil {
if errors.Is(err, ErrNotFound) {
fmt.Println("Resource was not found")
}
fmt.Println("Original error:", err)
fmt.Println("Unwrapped error:", errors.Unwrap(err))
}
}
Error HandlingBest Practices
Go · IntermediateSnippet

Non-Blocking Channel Operations with Select

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.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
import "fmt"
func main() {
messages := make(chan string)
signals := make(chan bool)
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
}
Async & ConcurrencyControl Flow
Go · IntermediateSnippet

Composition via Struct Embedding

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.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
import "fmt"
type User struct {
ID int
Name string
}
func (u User) Greet() {
fmt.Printf("Hello, I am %s\n", u.Name)
}
type Admin struct {
User // Embedded field
Level int
}
func main() {
a := Admin{
User: User{ID: 1, Name: "Alice"},
Level: 10,
}
a.Greet() // Promoted method
fmt.Println("ID:", a.ID) // Promoted field
}
SyntaxDesign Patterns
Go · IntermediateSnippet

Resource Safety with Defer and Panic Recovery

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.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
func protectedFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("something went wrong")
fmt.Println("This will never run")
}
Error HandlingControl Flow
Go · IntermediateSnippet

Optimizing Performance with Slice Capacity

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.

snippet.go
go
1
2
3
4
5
6
7
8
func efficientAppend() {
// Pre-allocate capacity to avoid multiple reallocations
data := make([]int, 0, 100)
for i := 0; i < 100; i++ {
data = append(data, i)
}
fmt.Println(len(data), cap(data))
}
Arrays & ListsPerformance
Go · IntermediateSnippet

Synchronizing Tasks with sync.WaitGroup

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 are complete.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
func processAll() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d started\n", id)
time.Sleep(time.Second)
}(i)
}
wg.Wait()
fmt.Println("All workers finished")
}
Async & ConcurrencyFunctions