Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Comparison {{< katex />}} ## Generics | Feature | Go | C++ | | :--- | :--- | :--- | | **Paradigm** | Parametric Polymorphism | Metaprogramming | | **Constraint** | Interface-based (Type Sets) | Concepts (C++20), SFINAE | | **Specialization** | Not Supported | Supported | | **Metaprogramming** | Not Supported | Turing-complete | {{% tabs "generics" %}} {{% tab "Go" %}} Go generics focus on simplicity and clarity. They use type parameters constrained by interfaces. ### Generic Function eg. ```go // T is constrained by 'any' func Print[T any](s []T) { for _, v := range s { fmt.Print(v, " ") } } // T is constrained by 'comparable' (supports == and !=) func Find[T comparable](s []T, val T) int { for i, v := range s { if v == val { return i } } return -1 } ``` ### Data Structure Syntax: `type STRUCT_NAME[ ] struct {}` eg. ```go type Stack[T any] struct { vals []T } func (s *Stack[T]) Push(val T) { s.vals = append(s.vals, val) } ``` ### Type Constraints - `any`: Alias for `interface{}`. Allows any type. - `comparable`: Predefined interface for types that support `==` and `!=`. - **Custom Interface**: Any interface can be used as a constraint. - **`~` Operator**: Used in interface definitions to match types with the same **underlying type**. eg. ```go type Integer interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 } func Add[T Integer](a, b T) T { return a + b } ``` {{% /tab %}} {{% tab "C++" %}} C++ templates are highly flexible and support complex metaprogramming, allowing for compile-time logic and optimization. ### Function Template eg. ```cpp template void Print(const std::vector& v) { for (const auto& i : v) { std::cout << i << " "; } } ``` ### Class Template eg. ```cpp template class Stack { private: std::vector vals; public: void Push(T val) { vals.push_back(val); } }; ``` {{% /tab %}} {{% /tabs %}} ## Slicing {{% tabs "slicing" %}} {{% tab "Python" %}} Python list slicing creates a shallow copy. Modifying the new list does not affect the original list. eg. ```python a = [1, 2, 3] b = a[:] b[0] = 9 print(a) # [1, 2, 3] ``` {{% /tab %}} {{% tab "Go" %}} Go slice slicing shares the same underlying array. Modifying the new slice affects the original slice. eg. ```go a := []int{1, 2, 3} b := a[:] b[0] = 9 fmt.Println(a) // [9 2 3] ``` {{% /tab %}} {{% /tabs %}} ## Switch {{% tabs "switch" %}} {{% tab "C" %}} - **Fall-through**: Cases fall through by default. A `break` statement is required to prevent falling through to the next case. - **Supported Types**: Only integer types such as `char`, `int`, and `long long` are supported. eg. ```c const char *words[] = {"a", "cow", "smile", "gopher", "octopus", "anthropologist"}; int num_words = sizeof(words) / sizeof(words[0]); for (int i = 0; i < num_words; i++) { size_t size = strlen(words[i]); switch (size) { case 1: case 2: case 3: case 4: printf("%s is a short word!\n", words[i]); break; case 5: printf("%s is exactly the right length: %zu\n", words[i], size); break; case 6: case 7: case 8: case 9: break; default: printf("%s is a long word!\n", words[i]); } } ``` {{% /tab %}} {{% tab "Go" %}} - **Fall-through**: Cases do not fall through by default. An explicit `fallthrough` keyword is required to force fall-through behavior. - **Supported Types**: Any type that can be compared with `==` is supported. This includes all built-in types except slices, maps, channels, functions, and structs that contain fields of these types. - **Multiple Values**: Multiple values can be matched in a single case using a comma-separated list. - **[Blank Switch]({{< relref "/programming/go/switch.md#blank-switch" >}})**: A switch without an expression is equivalent to `switch true`. Useful for clean `if-else-if` chains. eg. ```go words := []string{"a", "cow", "smile", "gopher", "octopus", "anthropologist"} for _, word := range words { switch size := len(word); size { case 1, 2, 3, 4: fmt.Println(word, "is a short word!") case 5: wordLen := len(word) fmt.Println(word, "is exactly the right length:", wordLen) case 6, 7, 8, 9: default: fmt.Println(word, "is a long word!") } } ``` {{% /tab %}} {{% /tabs %}} ## Variadic / Unpacking {#variadic-unpacking} | Feature | C | C++ | Go (`...`) | Python (`*`) | | :--- | :--- | :--- | :--- | :--- | | **Declaration: Packing** | `void f(int n, ...)` — `` |
  • Heterogeneous: `Args&&... args` — Variadic Template
  • Homogeneous: `initializer_list`
  • C-compat: `...`
| `func f(args ...T)` | `def f(*args, **kwargs):` | | **Call Site: Unpacking** | Not Supported — requires `va_list` wrapper | `f(args...)`, `f(PATTERN...)` — Pack Expansion | `f(slice...)` | `f(*seq, **dict)` | | **Evaluation / Mechanism** | Runtime stack traversal via `va_list`, single function |
  • `Args...`: **Compile-time** instantiation per argument combination, zero runtime overhead
  • `initializer_list`: lightweight `const` array view
| Allocates runtime Slice `[]T`, single function | Allocates runtime `tuple` / `dict`, single function | | **Type Safety** | ❌ No type or count check, runtime UB on mismatch | ✅ `Args...` enforces 100% compile-time type safety across **heterogeneous types** with Perfect Forwarding | Single type `T` only, heterogeneous types require `...any` boxing | Dynamic typing, resolved at runtime | | **Unpacking Capability** | Not Supported | **Full pattern replication**: `wrap(args)...` → `wrap(a1), wrap(a2)` and C++17 Fold Expressions `(args + ...)` | Unpacks slice elements as-is only | Unpacks iterable/mapping elements as-is only | {{% tabs "variadic-unpacking" %}} {{% tab "C" %}} C handles variadic functions using macros defined in the `` header. ### Declaration: Packing - Requires at least one named fixed parameter, followed by `...` as the final parameter. - Iterates over arguments using `va_list`, `va_start`, `va_arg`, and `va_end`. - The compiler performs no type or argument count checking; callers must communicate the count explicitly or via format strings. eg. ```c #include #include void print_ints(int count, ...) { va_list args; va_start(args, count); for (int i = 0; i < count; i++) { int val = va_arg(args, int); printf("%d ", val); } va_end(args); printf("\n"); } int main() { print_ints(3, 10, 20, 30); return 0; } ``` ### Call Site: Unpacking C does not support syntax-level argument unpacking. Arrays cannot be unpacked into variadic calls directly; a separate function accepting a `va_list` such as `vprintf` must be provided. {{% /tab %}} {{% tab "C++" %}} C++ provides distinct mechanisms for handling varying numbers of arguments depending on type homogeneity and compile-time vs. runtime semantics. ### Variadic Templates (`Args...`, C++11) Accepts zero or more heterogeneous arguments and instantiates specialized functions at compile time with no runtime container overhead (see [Templates: Variadic Templates]({{< relref "/programming/cpp/primer/templates.md#3-variadic-templates-args-and-emplace_back" >}}) for details). - **Declaration: Packing (`typename... Args`, `Args&&... args`):** Placing `...` before the name packs types or function arguments together. - **Call Site: Unpacking (`PATTERN...`):** Placing `...` after an expression replicates the entire pattern to the left for each element, separated by commas. eg. ```cpp #include #include template auto MySum(Args... args) { return (args + ...); // C++17 Fold Expression: expands to (arg1 + (arg2 + arg3)) } template T Create(Args&&... args) { // Replicates the full pattern: std::forward(arg1), std::forward(arg2), ... return T(std::forward(args)...); } int main() { std::cout << MySum(1, 2.5, 3) << '\n'; // 6.5 (heterogeneous: int, double, int) return 0; } ``` ### `std::initializer_list` (C++11) Used when all variable arguments share the same type. - Unlike `vector`, elements in an `initializer_list` are always **`const`**. - Provides `.begin()` and `.end()` member functions, allowing **traversal via range `for` loops**. eg. ```cpp #include #include #include void PrintMessages(std::initializer_list il) { for (const auto &elem : il) { // range for supported via .begin() and .end() std::cout << elem << " "; } std::cout << '\n'; } int main() { PrintMessages({"hello", "world", "c++"}); // Pass arguments in braced list return 0; } ``` ### Ellipsis Parameter (`...`) C-compatible variadic syntax (`printf`, etc.). Offers no type safety and should be avoided in modern C++. {{% /tab %}} {{% tab "Go" %}} ### Declaration: Packing eg. ```go func mySum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } func main() { fmt.Println(mySum(1, 2, 3)) } ``` ### Call Site: Unpacking eg. ```go func main() { s := []int{1, 2, 3} s = append(s, s...) fmt.Println(s) // [1, 2, 3, 1, 2, 3] } ``` {{% /tab %}} {{% tab "Python" %}} ### Declaration: Packing eg. ```python def mySum(*args): return sum(args) if __name__ == "__main__": print(mySum(1, 2, 3)) ``` ### Call Site: Unpacking eg. ```python def mySum(*args): return sum(args) if __name__ == "__main__": print(mySum(1, 2, 3)) print(mySum(*[1, 2, 3])) ``` {{% /tab %}} {{% /tabs %}} ## Exception Handling {#exception-handling} | Feature | Python | C++ | | :--- | :--- | :--- | | **Syntax** | `try - except - else - finally` | `try - catch` (No `finally`; relies on RAII) | | **Throwable Types** | Must derive from `BaseException` | Any type (primitives like `int`, strings, class objects) | | **Catch-all** | `except:` or `except Exception:` | `catch (...)` (Ellipsis) | | **Uncaught Exception** | Prints traceback and exits interpreter | Propagates up call stack; calls `std::terminate()` $\rightarrow$ `abort()` | | **Resource Cleanup** | `finally` block, `with` statement (Context Manager) | **RAII** (local destructors automatically invoked during stack unwinding) | | **Idiom / Philosophy** | EAFP (actively used for standard control flow) | Zero-cost model (reserved exclusively for truly exceptional errors) | {{% tabs "exception-handling" %}} {{% tab "Python" %}} Python exception handling is built around the **EAFP** ("Easier to ask for forgiveness than permission") idiom. Exceptions are widely used not only for error handling but also for ordinary control flow (such as `StopIteration` signaling the completion of an iterator). - **`else` block**: Executes only if no exception was raised in the `try` block. - **`finally` block**: Always executes regardless of whether an exception occurred or was handled; commonly used for cleanup. - **`with` statement (Context Manager)**: Safely releases resources via `__enter__` and `__exit__` even if exceptions occur. - All exception objects must derive from `BaseException` (typically subclassing `Exception`). eg. ```python def divide(a, b): try: result = a / b except ZeroDivisionError as e: print("Cannot divide by zero:", e) except Exception as e: print("Unexpected error:", e) else: print("Calculation successful:", result) finally: print("Cleanup block always executed") divide(10, 2) divide(10, 0) ``` {{% /tab %}} {{% tab "C++" %}} C++ exception handling is designed strictly for truly exceptional error conditions. While it imposes no runtime overhead on successful execution (**Zero-cost exception** model), throwing an exception incurs significant runtime cost due to stack unwinding. - **Handler Search and Propagation (Stack Unwinding)**: If the current `try` block's `catch` clauses do not provide a matching type, the exception propagates up to the caller function, unwinding the stack and calling destructors for all local objects along the way. - **Uncaught Exception**: If no matching handler is found anywhere in the call chain up to `main()`, the runtime invokes **`std::terminate()`**, which by default calls **`abort()`** to immediately terminate the program. - **RAII Instead of `finally`**: C++ lacks a `finally` block. Instead, it relies on **RAII (Resource Acquisition Is Initialization)**: destructors of stack-allocated objects are automatically executed during stack unwinding to release resources. - **Arbitrary Throwable Types**: Any type can be thrown—including primitives like `int`, string literals, or custom class objects. Standard practice strongly recommends throwing types derived from `std::exception` and catching by reference: **`catch (const std::exception &e)`** to prevent object slicing. - **`catch (...)`**: The universal catch-all handler (ellipsis) that matches any exception type. eg. ```cpp #include #include void Process(int val) { if (val < 0) { throw std::invalid_argument("Negative values not allowed"); } if (val == 0) { throw 0; // Primitive types can also be thrown } } int main() { try { Process(-1); } catch (const std::invalid_argument &e) { std::cerr << "Invalid argument: " << e.what() << '\n'; } catch (int errCode) { std::cerr << "Caught error code: " << errCode << '\n'; } catch (...) { // Universal catch-all handler std::cerr << "Caught unknown exception\n"; } return 0; } ``` {{% /tab %}} {{% /tabs %}}