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/ # Interface ## Pointer Parameters and Interfaces Based on *Learning Go, 2nd ed.*: > The only time you should use pointer parameters to modify a variable is when the function expects an interface. When a function expects an interface, you must pass a pointer if the implementation of that interface uses pointer receivers. ## The `any` Type The `any` type is an alias for `interface{}` and can represent any value. > The value passed in for the `any` parameter must be a pointer. If it is not, an error is returned. This is common in functions that need to modify the passed-in value, such as `json.Unmarshal`. eg. ```go var m map[string]any data := []byte(`{"name": "joe"}`) err := json.Unmarshal(data, &m) // Pass as a pointer ``` ## Method Sets The method set of a type determines which methods can be called on an instance of that type. ### Receiver Rules - The method set of a pointer instance (`*T`) contains methods defined with both pointer (`*T`) and value (`T`) receivers. - The method set of a value instance (`T`) contains only methods defined with value (`T`) receivers. ### Automatic Address-taking When calling a method on a local variable that is a value type, Go automatically takes the address of the variable if the method has a pointer receiver. eg. ```go type Counter struct { count int } func (c *Counter) Increment() { c.count++ } func main() { c := Counter{} c.Increment() // Automatically converted to (&c).Increment() } ``` ### Interface Restriction: Why Interfaces Cannot Automatically Take Addresses For a local variable `c.Increment()`, Go can easily take the address on the stack and transform it into `(&c).Increment()`. However, the moment a value is assigned to an interface (`var i Incrementer = c`), **a copy of the value is stored inside the interface (Boxed Value)**: - According to the Go language specification, values stored inside an interface are **unaddressable** to prevent memory corruption and ensure type safety. - Because their address cannot be taken (`&`), there is no way to invoke a pointer receiver method (`Increment`) through the interface. - Conversely, `&c` is already a pointer (memory address). When invoking a value receiver method, Go can always dereference the pointer (`*p`) safely. > **Golden Rule** > **If an interface requires even a single method declared with a pointer receiver, you must assign a pointer (`&struct{}`) to that interface.** > Because the method set of a pointer type (`*T`) includes both value and pointer receiver methods, pointer types satisfy interfaces much more easily and have a wider compatibility range than value types (`T`). eg. (Mixing Value and Pointer Receivers) ```go type Worker interface { Work() // Value receiver Stop() // Pointer receiver } type Robot struct{} func (r Robot) Work() {} func (r *Robot) Stop() {} func main() { // Compile Error: Robot does not implement Worker (Stop method has pointer receiver) // var w1 Worker = Robot{} // Compile Success: The method set of *Robot contains both Work() and Stop() var w2 Worker = &Robot{} w2.Work() w2.Stop() } ``` ## Interface and Nil In the Go runtime, interfaces are implemented as a struct with two pointer fields: one for the **value** and one for the **type** of the value. ### Nil Interface Rules - **Both fields must be nil:** For an interface to be considered `nil`, both the type and the value fields must be `nil`. - **Non-nil type makes non-nil interface:** As long as the type field is non-nil, the interface is non-nil (even if the value field is `nil`). - **Meaning of Nil:** For an interface type, `nil` indicates whether you can safely invoke methods on it. eg. ```go var i Incrementer // type: nil, value: nil -> i is nil var c *Counter // c is nil i = c // type: *Counter, value: nil -> i is NOT nil ``` ## Type Assertion A type assertion provides access to an interface value's underlying concrete value. ### Comma OK Idiom A type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded. This is often called the "comma ok" idiom. eg. ```go var i any = "hello" s, ok := i.(string) if ok { fmt.Println(s) } ``` If the type assertion fails and the boolean value is not captured, the program will panic. eg. ```go var i any = 42 s := i.(string) // Panics ``` ### Runtime Check Type assertions are checked at runtime. The compiler cannot always determine if a type assertion will succeed. ## Type Switch A type switch is a construct that permits several type assertions in series. eg. ```go func do(i any) { switch v := i.(type) { case int: fmt.Printf("Twice %v is %v\n", v, v*2) case string: fmt.Printf("%q is %v bytes long\n", v, len(v)) default: fmt.Printf("I don't know about type %T!\n", v) } } ``` ### The `i.(type)` Syntax The `i.(type)` syntax is only valid within a `switch` statement. Using it elsewhere will result in a compilation error. ## Interface Comparability Interfaces are comparable. - Two instances of an interface type are equal only if their types are equal and their values are equal. - A comparison panics if the underlying type is non-comparable (eg. slice, map, function). eg. ```go type Doubler interface { Double() } type DoubleInt int func (d *DoubleInt) Double() { *d = *d * 2 } type DoubleIntSlice []int func (d DoubleIntSlice) Double() { for i := range d { d[i] = d[i] * 2 } } func DoublerCompare(d1, d2 Doubler) { fmt.Println(d1 == d2) } func main() { var di DoubleInt = 10 var di2 DoubleInt = 10 var dis = DoubleIntSlice{1, 2, 3} var dis2 = DoubleIntSlice{1, 2, 3} DoublerCompare(&di, &di2) // false, the values are different DoublerCompare(&di, dis) // false, the types do not match DoublerCompare(dis, dis2) // panic, slices are uncomparable } ```