Types, interfaces, errors, slices/maps, modules, testing
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeA value receiver gets a copy of the struct, so changes inside the method don't affect the original. A pointer receiver gets a reference, so changes are visible outside the method. Use pointer receivers when you want to modify the struct or avoid copying large structs.
A type satisfies an interface by implementing all the methods in the interface. There's no explicit declaration; if the method set matches, the type implicitly implements the interface.
You use the two-value assignment: v, ok := m[key]. If ok is true, the key exists; otherwise, it doesn't.
defer keyword?defer schedules a function to run after the surrounding function returns. It's commonly used for cleanup, like closing files or unlocking mutexes.
A slice has a capacity, which is the size of its underlying array. If you append elements and exceed the capacity, Go allocates a new array and copies the data. This can lead to slices that no longer share the same backing array, so changes to one slice won't affect the other.
You wrap errors using fmt.Errorf with the %w verb. This adds context to the error while preserving the original error, allowing you to check error chains with errors.Is or errors.As. It's useful for debugging and handling specific error types.
Table-driven tests use a slice of test cases and loop over them, running the same logic for each case. They're preferred because they make tests concise, scalable, and easy to maintain, especially when testing multiple input/output combinations.
You run go mod init <module-path> to create a module, then use go get <package> to add a dependency. The go.mod file tracks dependencies and their versions.
Writing to a nil map causes a runtime panic. You need to initialize the map with make or a literal before writing to it.
Go uses explicit error values returned from functions, rather than exceptions. This makes error handling more predictable and encourages checking errors at each step, rather than relying on catch blocks.
recover in Go?recover is used in a deferred function to catch a panic and prevent the program from crashing. It's useful for handling unexpected errors gracefully, but should be used sparingly.
You use errors.As to check if an error in the chain matches a specific type. For example, var myErr *MyError; if errors.As(err, &myErr) { /*...*/ } lets you handle custom error types.