Basic Function Syntax
A function in Go is declared using thefunc keyword, followed by the function name, parameters, return type, and body.
Function names that start with a capital letter (like
Add) are exported and can be used by other packages. Lowercase names are private to the package.Multiple Return Values
One of Go’s most powerful features is the ability to return multiple values from a function. This pattern is used extensively throughout the language, especially for error handling. Here’s how to return multiple values:Functions as First-Class Citizens
In Go, functions can be:- Assigned to variables
- Passed as arguments to other functions
- Returned from other functions
Passing Functions as Arguments
You can pass a function as a parameter by specifying its signature:The parameter
fn func(int, int) int means: “a function that takes two ints and returns an int”.Complete Example
Here’s a complete program demonstrating all these concepts:Key Takeaways
Multiple Returns
Go functions can return multiple values, making error handling explicit and natural.
First-Class Functions
Functions can be passed as arguments, enabling flexible and reusable code patterns.
Clear Signatures
Function types like
func(int, int) int make it clear what a function accepts and returns.No Parentheses
Unlike many languages, Go doesn’t require parentheses around return types in multi-value returns.