Functions Cheatsheet
Basic Syntax
func Name(p1 Type, p2 Type) ReturnType {
return val
}
Parameter Shorthand
func add(x, y int) int { ... } // Both x and y are ints
Return Patterns
- Multiple Returns:
func get() (int, int) { ... }
- Named Returns:
func get() (x, y int) { ... }
- Blank Identifier:
x, _ := get() (Ignore second return)
Special Keywords
defer: Runs at the end of the function (LIFO order).
return: Ends function execution. “Naked” returns return named values.
Functional Patterns
- Higher-Order: Function taking/returning another function.
- Anonymous:
func(x int) { ... }(10) (Inline definition).
- Closure: Inner function referencing outer variables.
Scoping
- Package: Accessible everywhere in the package.
- Function: Local to the function.
- Block: Local to
{ } (if, for, etc.).
- Pass by Value: Functions always get a copy of the arguments.