This guide covers Go best practices demonstrated throughout the Learn Go course materials. These patterns are extracted from thousands of examples and represent idiomatic Go code.
Package names should be short, concise, and descriptive. The package name becomes part of the API (e.g., logparser.Parse is clearer than utils.ParseLog).
// Ignore index with _for _, value := range slice { fmt.Println(value)}// Index onlyfor i := range slice { fmt.Println(i)}// Count itemsvar count intfor range slice { count++}
When slicing, remember that the backing array is still referenced. This can cause memory leaks.
// From 16-slices/exercises/24-fix-the-memory-leak// If you only need a small portion, copy itsmall := make([]byte, 10)copy(small, large[:10])// Now large can be garbage collected
// Use pointers to modify valuesvar counter byte = 100P := &counter*P = 25 // counter is now 25// Use values for copiesV := *PV = 200 // counter unchanged
// Parse extracts structured data from a log line.// It returns an error if the line format is invalid.func Parse(line string) (*Entry, error) { // ...}
Package-level comments should start with “Package packagename” and explain the package’s purpose.