Functions
Syntax
The syntax for function is really simple in Go, it starts with func
1 | // definition |
To define a math operator function
1 | package main |
Return Multiple Results
Similar to Python, Go functions can return multiple results
1 | func div(a, b int) (int, int){ |
The results will be
1 | 2 1 |
We may also assign names to the returned value
1 | func div(a, b int) (q, r int) { |
The output results will be
1 | 3 1 |
What if the function returns multiple results, but we just need to use one of them? As Go is strict on varialbe definition.
Once a variable is defined, it must be used in the code. We could use _
to take the unwanted result
1 | func div(a, b int) (q, r int) { |
We could use this feature to rewrite the operator function with more informative error message
1 | func eval3(a, b int, op string) (int, error) { |
The output will be:
1 | Operator Not Recongized: x |
Functional Programming
Go supports functional programming, we could refactor the above function with nested function
1 | package main |
The output will be:
1 | Calling Function main.pow with args (8, 3) and results = 512 |
In the output above, main
is the package name, pow
is the function name.
Alternatively, we could invoke apply
with anonymous function
1 | func main() { |
The output will be:
1 | Calling Function main.main.func1 with args (7, 6) and results = 117649 |
The first main
is the package name, the second main
is the function name, since it’s invoked in main
function. func1
is due to anonymous function.
Unfortunately, Go doesn’t have something fancy such as lambda
in Python or Java.
Go *args
In Go, there are something similar to Non-Keyword Arguments *args
in Python. We could use ...
in parameters in function definition.
1 | func mysum(numbers ...int) int { |
The output results will be:
1 | 55 |
To summarize
- The returned type is at the back of function declaration
- Can return multiple values
- A function can take other functions as parameters
- No default parameters or optional parameters
- Can use
...
to declare variable parameters, similar to*args
in Python