Functions
Sample code link: (https://repl.it/@jjoco/go-functions)
Declaring Functions
Go's function declaration uses the func
keyword, and the dev can specify input and output parameter types.
1 2 3 |
|
Syntax notes:
- function => func
- No colons between variable name and its type
Example: Get hypotenuse of triangle given leg lengths
1 2 3 4 |
|
Defer
The defer keyword is used to run a statement after the current function has returned. You might want to use this if, for example, you had a port listener and you wanted to close it after a function returns.
Sample usage:
1 2 3 4 5 6 |
|
Variadic Functions
You can define a function to have a variable amount of arguments (of the same type) like the following:
1 2 3 4 5 6 7 |
|
This allows functions like append to have a variable amount of elements to add into a slice.
In calling function:
1 2 3 |
|
- Use
...elementType
in function signature to denote a varying amount of arguments of elementType - Use
elementArr...
to unpack the elements in elementArr into function's input