Go Functions: Difference between revisions
(45 intermediate revisions by the same user not shown) | |||
Line 32: | Line 32: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func someFunction(color string, size int) (float64, error) { | func someFunction(color string, size int) (float64, error) { | ||
// | // | ||
// body | // body | ||
Line 45: | Line 46: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Parameters== | ==Parameters== | ||
The parentheses optionally enclose function parameters. A function may not have any parameters, but | The parentheses optionally enclose function parameters. A function may not have any parameters, but the parentheses must still be provided. The parameters, when exist, are vehicles for the input data the function needs to operate on. The parameter declaration syntax consists in a set of variables listed after the function name, between parentheses. Parameters become local variables to the function, scoped to the function body. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
...(<par_name_1> <type>, <par_name_2> <type>, ...) | ...(<par_name_1> <type>, <par_name_2> <type>, ...) | ||
Line 66: | Line 67: | ||
{{Internal|Variables,_Parameters,_Arguments#Variable|Variables, Parameters, Arguments}} | {{Internal|Variables,_Parameters,_Arguments#Variable|Variables, Parameters, Arguments}} | ||
===Parameter Naming=== | ===Parameter Naming=== | ||
Function parameters | Function parameters are like local variables, so they should be named according to the naming conventions for variables. They also serve as documentation. When their types are descriptive, the names should be short: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func SomeFunc(d Duration, f func()) error | func SomeFunc(d Duration, f func()) error | ||
Line 76: | Line 77: | ||
==Return Declaration== | ==Return Declaration== | ||
The function output | The function output may have a type (or types), which are listed in the function declaration after the parameter list. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func ...(...) | func ...(...) [return-type] { | ||
... | ... | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
If the function has more than one return values, their types must be enclosed in parentheses. | ===Multiple Return Values=== | ||
In Go, functions can return multiple values. If the function has more than one return values, their types must be enclosed in parentheses. | |||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func ...(...) (<return-type-1>, <return-type-2>, ....) { | func ...(...) (<return-type-1>, <return-type-2>, ....) { | ||
Line 88: | Line 91: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=== | This capability is typically used to return one or more results and an error, in case the function produces an error. This is a common style, used throughout. Also see: {{Internal|Go_Language_Error_Handling#Error_Basics|Error Handling}} | ||
===<span id='Return_Value_Naming'></span>Named Result Parameters=== | |||
The return or result "parameters" can be given names and used as regular variables, just like the input parameters. When the result parameters are named, they are initialized to zero values for their types when the function begins. If the function executes a <code>return</code> statement with no arguments, the current values of the result parameters are used as result values. This is known as a [[#Naked_return|"naked" return]]. The return parameters of exported functions should be named for documentation purposes: | |||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func Copy(dst Writer, src Reader) (written int64, err error) | func Copy(dst Writer, src Reader) (written int64, err error) | ||
Line 106: | Line 110: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
{ | { | ||
... | |||
return someVar | return someVar | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<span id='Multi-Value_Return'></span>More than one values can be returned at the same time, and such a function can be used with the [[ | <span id='Multi-Value_Return'></span>More than one values can be returned at the same time, and such a function can be used with the [[Go_Variables#Multi-Value_Short_Variable_Declaration|multi-value short variable declaration form]]. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
{ | { | ||
Line 127: | Line 131: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
===Naked <tt>return</tt>=== | ===Naked <tt>return</tt>=== | ||
A <code>return</code> statement without any arguments returns the | A <code>return</code> statement without any arguments returns the [[#Named_Result_Parameters|named result parameters]]. It is known as a "naked return": | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func someFunc(...) (result string, err error) { | func someFunc(...) (result string, err error) { | ||
Line 134: | Line 138: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Function Parameters and Return Value Scope== | ==Function Parameters and Return Value Scope== | ||
The scope of the function parameters and the return values is the same as the function body, even though they appear lexically outside the braces that enclose the function body. | |||
=Invocation= | =Invocation= | ||
Line 156: | Line 161: | ||
This semantics is not available in Go. In Go, function arguments are '''always passed by value''', there is no other choice, and the fact that Go [[Go_Language#.28No.29_Reference_Variables|does not have reference variables]] makes it impossible for the function to modify the original values. When the call arguments are copied on the function’s stack, the function always deals with copies, no reference variables exist, and this makes the function unable to change the values present outside the function. | This semantics is not available in Go. In Go, function arguments are '''always passed by value''', there is no other choice, and the fact that Go [[Go_Language#.28No.29_Reference_Variables|does not have reference variables]] makes it impossible for the function to modify the original values. When the call arguments are copied on the function’s stack, the function always deals with copies, no reference variables exist, and this makes the function unable to change the values present outside the function. | ||
This approach promotes '''encapsulation''': the function cannot modify the original data. The called function cannot changed the variables inside the calling function. On the flip-side, the approach comes at the cost of the argument copy time, which for large pieces of data, can be non-trivial. In the particular case of arrays, they are [[Go_Arrays#Arrays_are_Values|passed by value]], like everybody else, their data is always copied, and for large arrays this can be a problem. This is the reason array should not be used directly, but [[Go_Slices# | This approach promotes '''encapsulation''': the function cannot modify the original data. The called function cannot changed the variables inside the calling function. On the flip-side, the approach comes at the cost of the argument copy time, which for large pieces of data, can be non-trivial. In the particular case of arrays, they are [[Go_Arrays#Arrays_are_Values|passed by value]], like everybody else, their data is always copied, and for large arrays this can be a problem. This is the reason array should not be used directly, but [[Go_Slices#Slices_and_Pass-by-Value|slices should be used instead]]. | ||
A manual alternative to “pass-by-reference” can be implemented by passing a pointer to a variable as argument. This mechanism is called '''pass-by-pointer'''. Go materials refer to it as “pass-by-reference”, but this is not technically correct. This is how pass-by-pointer is implemented: | A manual alternative to “pass-by-reference” can be implemented by passing a pointer to a variable as argument. This mechanism is called '''pass-by-pointer'''. Go materials refer to it as “pass-by-reference”, but this is not technically correct. This is how pass-by-pointer is implemented: | ||
Line 171: | Line 176: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
The same considerations apply when returning results from a function. The result can be returned by value or by pointer. One practical advantage of returning by pointer is that the function can return <code>nil</code> instead of allocating an "empty" value and returning it when the function errors out. | |||
Also see: {{Internal|Python_Language_Functions#Pass_by_Value_and_Pass_by_Reference|Pass by Value and Pass by Reference in Python}} | Also see: {{Internal|Python_Language_Functions#Pass_by_Value_and_Pass_by_Reference|Pass by Value and Pass by Reference in Python}} | ||
Line 194: | Line 199: | ||
=Variadic Functions= | =Variadic Functions= | ||
Variadic function are functions with a variable number of parameters. They are declared with an ellipsis <code>...</code> that precedes the type of the parameter. Inside the function, the parameter is treated like a slice. There could be just '''one''' variadic argument per function, which must be the final argument in the list. | Variadic function are functions with a variable number of parameters. They are declared with an ellipsis <code>...</code> that precedes the type of the parameter. Inside the function, the parameter is treated like a slice of the parameter's type. There could be just '''one''' variadic argument per function, which must be the final argument in the list. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func SomeVariadicFunc(s string, i ...int) { | func SomeVariadicFunc(s string, i ...int) { | ||
Line 209: | Line 214: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Invoking Variadic Functions with Slices== | |||
A variadic function expects a variable number of arguments of the same type when invoked. If the values of those arguments are packed in a slice of those type, there is a syntax shorthand that allows us to use that slice as an argument of the variadic function. The syntax consists in ellipsis <code>...</code> attached to the name of the slice variable. | |||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
ii := []int{1, 2, 3} | |||
SomeVariadicFunc("blue", | SomeVariadicFunc("blue", ii...) // equivalent with invoking SomeVariadicFunction("blue", 1, 2, 3) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=<span id='Deferred_Function_Calls'></span><span id='defer'></span><tt>defer</tt> - Deferred Function Calls= | =<span id='Deferred_Function_Calls'></span><span id='defer'></span><tt>defer</tt> - Deferred Function Calls= | ||
Go syntax allows specifying that a function invocation should be deferred after the function that invokes it finishes executing. This behavior is achieved using the <code>[[Go_Language#defer_keyword|defer]]</code> keyword. This mechanism is usually used to clean things up after the enclosing function completes, close files, etc. | Go syntax allows specifying that a function invocation should be deferred after the function that invokes it finishes executing. This behavior is achieved using the <code>[[Go_Language#defer_keyword|defer]]</code> keyword. This mechanism is usually used to clean things up after the enclosing function completes, close files, etc. Deferring a call to a function has two advantages. First, it guarantees that you will never forget to close the file, a mistake that is easy to make if you later edit the function and add a new return path. Second, it means that the deferred invocation sits near the operation that requires it, which is much clearer than placing it at the end of the function. | ||
Deferred invocation without arguments: | Deferred invocation without arguments: | ||
Line 274: | Line 282: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==<tt>defer</tt> and <tt>panic</tt>== | ==<tt>defer</tt> and <tt>panic</tt>== | ||
The function invoked with <code>defer</code> execute even in case of <code | The function invoked with <code>defer</code> execute even in case of <code>[[Go_panic#Overview|panic]]</code>. | ||
=Functions as First-Class Values= | =Functions as First-Class Values= | ||
Line 367: | Line 332: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==<span id='Lambda'></span><span id='Anonymous_Functions'></span>Anonymous Functions (Lambdas)== | ==<span id='Lambda'></span><span id='Anonymous_Functions'></span>Anonymous Functions (Lambdas)== | ||
Anonymous functions are also known as are lambdas. | |||
In the example for [[#Passing_a_Function_as_Argument_into_a_Function|Passing a Function as Argument into a Function]], we can simply create the function passed as argument on the fly, without giving it a name: | In the example for [[#Passing_a_Function_as_Argument_into_a_Function|Passing a Function as Argument into a Function]], we can simply create the function passed as argument on the fly, without giving it a name: | ||
Line 443: | Line 408: | ||
The most useful feature of overloading, the call of function with optional arguments and inferring defaults for those omitted can be simulated using variadic functions. | The most useful feature of overloading, the call of function with optional arguments and inferring defaults for those omitted can be simulated using variadic functions. | ||
=Built-in Functions= | |||
Built-in functions are available by default, without importing any package. Their names are [[Go_Language#Pre-Declared_Functions|predeclared function identifiers]]. They give access to Go's internal data structures. Their semantics depends on the arguments. | |||
:::{|class="wikitable" style="text-align: left;" | |||
| <font face='menlo' size='-2'>[[Go Slices#append.28.29|append()]]</font> || <font face='menlo' size='-2'>[[#cap.28.29|cap()]]</font> || <span id='close'></span><font face='menlo' size='-2'>[[Go_Channels#close|close()]]</font> || <font face='menlo' size='-2'>[[Go Built-In Functions for Manipulating Complex Numbers#complex.28.29|complex()]]</font> || <font face='menlo' size='-2'>[[Go Slices#copy.28.29|copy()]]</font> | |||
|- | |||
| <font face='menlo' size='-2'> [[Go Maps#delete.28.29|delete()]]</font> || <font face='menlo' size='-2'> [[Go Built-In Functions for Manipulating Complex Numbers#imag.28.29|imag()]]</font> || <font face='menlo' size='-2'> [[#len.28.29|len()]]</font> || <font face='menlo' size='-2'> [[#make.28.29|make()]]</font> || <font face='menlo' size='-2'> <span id='new'></span>[[#new()|new()]]</font> | |||
|- | |||
| <font face='menlo' size='-2'> [[Go Language Error Handling#Panics|panic()]]</font> || <font face='menlo' size='-2'> [[Go_Printing_to_Stdout_and_Stderr#print.28.29|print()]]</font> || <font face='menlo' size='-2'>[[Go_Printing_to_Stdout_and_Stderr#println.28.29|println()]]</font> || <font face='menlo' size='-2'> [[Go Built-In Functions for Manipulating Complex Numbers#real.28.29|real()]]</font> || <font face='menlo' size='-2'> [[Go Language Error Handling#Panics|recover()]]</font> | |||
|- | |||
|} | |||
==Length and Capacity== | |||
{{External|https://golang.org/ref/spec#Length_and_capacity}} | |||
===<tt>len()</tt>=== | |||
<code>len()</code> returns [[Go_Strings#String_Length|string length]], [[Go_Arrays#Array_Length|array length]], [[Go_Slices#len.28.29|slice length]] and [[Go_Maps#Map_Size|map size]]. | |||
===<tt>cap()</tt>=== | |||
<code>cap()</code> returns [[Go_Slices#cap.28.29|slice capacity]]. | |||
==Allocation== | |||
Go has two allocation primitives that do different things and apply to different types: the built-in functions <code>[[#new()|new()]]</code> and </code>[[#make()|make()]]</code>. | |||
===<tt>new()</tt>=== | |||
<code>new(T)</code> allocates memory for the specified type, fills it with the zero value for the type and returns a pointer to the newly allocated memory, a value of type <code>*T</code>. The memory allocated with new is automatically garbage collected. | |||
<syntaxhighlight lang='go'> | |||
var p *T | |||
p = new(T) | |||
</syntaxhighlight> | |||
<code>new()</code> can be used to [[Go_Structs#Initialization|initialize structs]]. The following expressions are equivalent: | |||
<syntaxhighlight lang='go'> | |||
new(T) | |||
*T{} | |||
</syntaxhighlight> | |||
It is good practice to design the type to be usable with its zero values, right away, without additional initialization if possible. See: {{Internal|Go_Structs#Make_Zero_Value_Useful|Make Zero Value Useful}} | |||
In some cases, this is not possible. Slices, maps and channels are types whose zeroed values are not useful, they require initialization before use, and this is where <code>[[#make()|make()]]</code> comes in. For example, <code>new([]int)</code> returns a pointer to a <code>nil</code>, while <code>make(int[], 1, 10)</code> returns a slice value that can be used right away. See <code>[[#make()|make()]]</code> below. | |||
Note that conventionally some packages expose <code>New()</code> functions to create the instances for their types. <code>New()</code> functions are written by users who control their semantics. | |||
===<tt>make()</tt>=== | |||
{{External|https://golang.org/ref/spec#Making_slices_maps_and_channels}} | |||
<code>make(()</code> is a [[#Built-in_Functions|built-in function]] that can be used to create and initialize [[Go_Slices#Slice_Initialization_with_make|slices]], [[Go_Maps#make.28.29|maps]] and [[Go_Channels#make()|channels]] only. It is different from <code>[[#new()|new()]]</code> in that it can be used with only these three types, initializes the instance to non-zero values, and returns a value of the type, '''not''' a pointer. The reason for the distinction is that these three types represent references to data structures that must be initialized before use. <code>make()</code> initializes the internal data structures and prepares the value for use. | |||
{{Internal|Go_Slices#Initialization_with_make()|Slice Initialization with <tt>make()</tt>}} | |||
{{Internal|Go_Maps#make.28.29|Map Initialization with <tt>make()</tt>}} | |||
{{Internal|Go_Channels#make()|Channel Initialization with <tt>make()</tt>}} | |||
==Slice Built-in Functions== | |||
===<tt>append()</tt>=== | |||
{{Internal|Go_Slices#append.28.29|<tt>append()</tt> Slices}} | |||
===<tt>copy()</tt>=== | |||
{{Internal|Go Slices#copy.28.29|<tt>copy()</tt> Slices}} | |||
==Map Built-in Functions== | |||
===<tt>delete()</tt>=== | |||
{{Internal|Go Maps#delete.28.29|delete()|<tt>delete()</tt> Map Elements}} | |||
==Panic Built-in Functions== | |||
:{|class="wikitable" style="text-align: left;" | |||
| <font face='menlo' size='-2'>[[Go_panic#Overview|panic()]]</font> || <font face='menlo' size='-2'>[[Go_panic#Recovering_after_a_Panic|recover()]]</font> | |||
|- | |||
|} | |||
==Type Conversion== | |||
{{Internal|Go_Language#Type_Conversion|Type Conversions}} | |||
==Complex Number Manipulation== | |||
:{|class="wikitable" style="text-align: left;" | |||
| <font face='menlo' size='-2'>[[go Built-In Functions for Manipulating Complex Numbers#complex.28.29|complex()]]</font> || <font face='menlo' size='-2'>[[go Built-In Functions for Manipulating Complex Numbers#real.28.29|real()]]</font> || <font face='menlo' size='-2'>[[go Built-In Functions for Manipulating Complex Numbers#imag.28.29|imag()]]</font> | |||
|- | |||
|} |
Latest revision as of 00:52, 24 August 2024
External
Internal
Overview
A function is a block of instructions, grouped together, and that optionally have a name.
Functions exist for code reusability reasons: the function is declared once and then can be invoked any number of times. The functions can be reused from within the project, or from other projects, if the function is declared as public and part of a package that is imported in the project that needs to use the function.
Function exist for abstraction reasons: they hide details into a compact "packaging" and improve the understandably of the code.
Naming
When consumed from other packages, the function references include package names, so in general, the function names should not be prefixed with the package name:
For rules around parameter naming, see Parameter Naming below. For rules around return value naming, see Return Value Naming below.
Go does not encourage Java-style getters and setters. For naming conventions around accessing struct fields, see:
Also see:
Declaration
A static function declaration starts with the func
keyword followed by the function name and a mandatory parentheses pair. Note that functions can also be created dynamically.
func <function_name>([parameters]) [(return_declaration)] {
// body
[return [return_values]]
}
func someFunction(color string, size int) (float64, error) {
//
// body
//
var result float64
var err error
// ...
return result, err
}
Parameters
The parentheses optionally enclose function parameters. A function may not have any parameters, but the parentheses must still be provided. The parameters, when exist, are vehicles for the input data the function needs to operate on. The parameter declaration syntax consists in a set of variables listed after the function name, between parentheses. Parameters become local variables to the function, scoped to the function body.
...(<par_name_1> <type>, <par_name_2> <type>, ...)
Example:
func blue(x int, s string) {
...
}
If there are multiple parameters of the same type, they can be provided as a comma separated list postfixed by the type:
func blue(x, y int, s string) {
...
}
Also see:
Parameter Naming
Function parameters are like local variables, so they should be named according to the naming conventions for variables. They also serve as documentation. When their types are descriptive, the names should be short:
func SomeFunc(d Duration, f func()) error
Web the types are more ambiguous, the names may provide documentation:
func Unix(sec, sec int64) Time
Return Declaration
The function output may have a type (or types), which are listed in the function declaration after the parameter list.
func ...(...) [return-type] {
...
}
Multiple Return Values
In Go, functions can return multiple values. If the function has more than one return values, their types must be enclosed in parentheses.
func ...(...) (<return-type-1>, <return-type-2>, ....) {
...
}
This capability is typically used to return one or more results and an error, in case the function produces an error. This is a common style, used throughout. Also see:
Named Result Parameters
The return or result "parameters" can be given names and used as regular variables, just like the input parameters. When the result parameters are named, they are initialized to zero values for their types when the function begins. If the function executes a return
statement with no arguments, the current values of the result parameters are used as result values. This is known as a "naked" return. The return parameters of exported functions should be named for documentation purposes:
func Copy(dst Writer, src Reader) (written int64, err error)
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
Function Body
Parameters are local variables visible inside the function body.
Go functions allow new local variables to be declared, inside the function, with the short variable declaration. The short variable declaration is not allowed anywhere else, except a function body.
The return Statement
The function returns its output value(s) with the return
keyword:
{
...
return someVar
}
More than one values can be returned at the same time, and such a function can be used with the multi-value short variable declaration form.
{
...
return someVar1, someVar2
}
Normally, one or more variable names are specified after the return
statement. The function will return the values associated with those variables, with the implication that the variables have been initialized before the return
statement. However, the value can be initialized in the return statement itself, like in this commonly-used pattern for constructor functions:
func NewBox(color string, ...) *Box {
return &Box{
color: color,
...
}
}
Naked return
A return
statement without any arguments returns the named result parameters. It is known as a "naked return":
func someFunc(...) (result string, err error) {
result = "..."
return // will return (result, err)
}
Function Parameters and Return Value Scope
The scope of the function parameters and the return values is the same as the function body, even though they appear lexically outside the braces that enclose the function body.
Invocation
All functions, except main()
must be invoked explicitly from the program to execute.
A function is invoked, or called, by specifying the function name, mandatory followed by open parentheses, optionally followed by arguments, if the function has parameters, then mandatory followed by closing parenthesis.
result, err := someFunction("blue", 3)
Arguments
The arguments consist of the data supplied to the function as part of the invocation.
Pass-by-value vs. pass-by-pointer vs. pass-by-reference
“Passing” in this context refer to how arguments are passed to parameters during a function call.
When a function is invoked, the function arguments are copied on the call stack.
In languages other than Go, the availability of reference variables allows for a “pass-by-reference” semantics, which means that even though a reference variable provided as argument is copied on the stack, the copy will still refer to the same target instance as the original function argument. The copied variable becomes just one more alias variable. The function is now in the position to the target instance directly, should it choose so.
This semantics is not available in Go. In Go, function arguments are always passed by value, there is no other choice, and the fact that Go does not have reference variables makes it impossible for the function to modify the original values. When the call arguments are copied on the function’s stack, the function always deals with copies, no reference variables exist, and this makes the function unable to change the values present outside the function.
This approach promotes encapsulation: the function cannot modify the original data. The called function cannot changed the variables inside the calling function. On the flip-side, the approach comes at the cost of the argument copy time, which for large pieces of data, can be non-trivial. In the particular case of arrays, they are passed by value, like everybody else, their data is always copied, and for large arrays this can be a problem. This is the reason array should not be used directly, but slices should be used instead.
A manual alternative to “pass-by-reference” can be implemented by passing a pointer to a variable as argument. This mechanism is called pass-by-pointer. Go materials refer to it as “pass-by-reference”, but this is not technically correct. This is how pass-by-pointer is implemented:
func passByPointerExample(i *int) {
*i = *i + 1
}
func callerFunction() {
x := 2
passByPointerExample(&x)
fmt.Println(x) // will print 3
}
The same considerations apply when returning results from a function. The result can be returned by value or by pointer. One practical advantage of returning by pointer is that the function can return nil
instead of allocating an "empty" value and returning it when the function errors out.
Also see:
main()
An executable program in Go must have a main()
function, where the program execution starts. The main()
function must be declared in the main
package. You never call this function. When a program is executed, the main()
gets called automatically.
package main
import "fmt"
func main() {
fmt.Printf("hello\n")
}
main()
is an implicit goroutine. For more details on main()
behavior as goroutine, and the interaction of other goroutines with main()
, see:
For more details on the main
package and Go executables, see:
init()
Variadic Functions
Variadic function are functions with a variable number of parameters. They are declared with an ellipsis ...
that precedes the type of the parameter. Inside the function, the parameter is treated like a slice of the parameter's type. There could be just one variadic argument per function, which must be the final argument in the list.
func SomeVariadicFunc(s string, i ...int) {
...
for _, v := range i {
...
}
}
When invoked, such a variadic function can get a list of arguments, separated by commas:
SomeVariadicFunc("blue", 3, 5, 7, 11, 13, 17)
Invoking Variadic Functions with Slices
A variadic function expects a variable number of arguments of the same type when invoked. If the values of those arguments are packed in a slice of those type, there is a syntax shorthand that allows us to use that slice as an argument of the variadic function. The syntax consists in ellipsis ...
attached to the name of the slice variable.
ii := []int{1, 2, 3}
SomeVariadicFunc("blue", ii...) // equivalent with invoking SomeVariadicFunction("blue", 1, 2, 3)
defer - Deferred Function Calls
Go syntax allows specifying that a function invocation should be deferred after the function that invokes it finishes executing. This behavior is achieved using the defer
keyword. This mechanism is usually used to clean things up after the enclosing function completes, close files, etc. Deferring a call to a function has two advantages. First, it guarantees that you will never forget to close the file, a mistake that is easy to make if you later edit the function and add a new return path. Second, it means that the deferred invocation sits near the operation that requires it, which is much clearer than placing it at the end of the function.
Deferred invocation without arguments:
defer func() {
fmt.Printf("do something\n")
}()
Deferred invocation with arguments:
defer closeDatabase(ctx, conn)
It is important to remember is that the deferred function arguments will be evaluated when the defer
statement is executed, NOT when the deferred function is executed.
More than one defer
statement can be specified in a function, and the order in which the deferred functions are executed is the inverse of the order in which the defer
statements have been declared (LIFO): the function declared with the last defer
statement is executed first, etc.
The following example prints:
EnclosingFunction 30
DeferredFunction 20
The example prints "EnclosingFunction 11" first because even if fmt.Println("EnclosingFunction", i)
statement is executed last in EnclosingFunction()
, DeferredFunction()
is executed after EnclosingFunction()
completes.
The example prints "DeferredFunction 20" last because first because DeferredFunction()
is executed after EnclosingFunction()
completes. However the integer value is the result of the argument evaluation at the time the defer
statement is executed (10 + 10), and not at the time DeferredFunction()
is executed, when it should have been 10 + 20 + 10 = 40.
func EnclosingFunction() {
i := 10
defer DeferredFunction(i + 10)
i += 20
fmt.Println("EnclosingFunction", i)
}
func DeferredFunction(i int) {
fmt.Println("DeferredFunction", i)
}
func main() {
EnclosingFunction()
}
defer and Error Handling
If the function being deferred returns an error value, not handing it is a mistake. Usually, IDE static analysis flags it as a strong warning. The error returned by deferred functions can be handled in a closure:
...
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
// handle the error here
log.Printf("%v\n", err)
}
}(resp.Body)
defer and panic
The function invoked with defer
execute even in case of panic
.
Functions as First-Class Values
Go implements features of a functional programming style. Function are treated as first-class value, which means functions are treated like any other type. Variables can be declared to be of a function type.
Function instances can be created dynamically at runtime, as opposite to declaring them statically in the program with the func
keyword. Functions can be passed as arguments into a function invocation and they can be returned as values of a function invocation. Functions can be stored into a data structure.
Declaring a Function Variable
The variable name acts as an alias, another name for the function.
var <var_name> <func_type>
A function type is declared using the following syntax:
func(<parameter_1_type, parameter_2_type, ...) (return_1_type, return_2_type, ...)
Example:
func SomeFunction(s string, i int) (int, error) {
...
}
...
var f func(string, int) (int, error)
f = SomeFunction
f("10", 20)
Passing a Function as Argument into a Function
func <func_name>(<func_var> <func_type_declaration>, ...) ... {
...
}
Example:
func Invoker(f func(string) int, s string) int {
result := f(s)
return result
}
func SomeFunction(s string) int {
i, _ := strconv.Atoi(s)
return i
}
...
result := Invoker(SomeFunction, "10")
...
Anonymous Functions (Lambdas)
Anonymous functions are also known as are lambdas.
In the example for Passing a Function as Argument into a Function, we can simply create the function passed as argument on the fly, without giving it a name:
result := Invoker(func(s string) int {
i, _ := strconv.Atoi(s)
return i
}, "10")
Returning Function as Result of Function Invocations
func FunctionMaker() func(int) int {
// we are creating an anonymous function
f := func(i int) int {
return i + 1
}
return f
}
Environment of a Function
The concept of environment of a function is important for understanding closures.
The environment of a function is the set of all names that are accessible from inside the function. Variables are a subset of those names. Given that Go is lexically scoped, the environment of a function includes the names defined locally in the function's own block and the enclosing blocks. A variable's scope is a somewhat similar concept, and scope and environment are some times used interchangeably when it comes to functions, but they are technically not the same. Functions have environments, variables have scope.
Closures
A closure is a function and its environment, which, as described in the Environment of a Function section, includes all the names declared within the function and all its enclosing blocks.
When a function is passed as an argument, the environment goes along with the function. When the function passed as argument is executed, the function has access to its original environment.
In the following example, we show that passing a function of an argument it passes the closure of the function: the function and its environment. The anonymous function that is passed as argument has access to its own localVar
local variable, the functionMakerVar
, declared in the block that also defines the anonymous function, and the package-level packageLevelVar
. When the anonymous function is invoked from within FunctionInvoker()
, whose environment does not have access to functionMakerVar
variable, the anonymous function still has access to all the variables it had access to while declared, and returns 10 (the argument) + 20 (localVar
in the anonymous function) + 30 (functionMakerVar
variable in the FunctionMaker()
block) + 40 (packageLevelVar
) = 100:
...
var packageLevelVar int = 40
func FunctionMaker() func(int) int {
functionMakerVar := 30
f := func(i int) int {
localVar := 20
return i + localVar + functionMakerVar + packageLevelVar
}
return f
}
func FunctionInvoker(f func(int) int, arg int) int {
return f(arg)
}
func main() {
f := FunctionMaker()
r := FunctionInvoker(f, 10)
fmt.Println(r) // will print 100
}
Elements of Style
Strive to write your functions so it enhances the understandability of your code. A code is understandable if, when you are in the position to find a feature, you can find it quickly. In general, you should be able to answer fast to question of type "Where is the code that does something?"
Avoid global variables. Without global variables, data is local to function.
Name functions and variables meaningfully. You don't want the names to be too long. "If you want to work with people, naming is really important".
Limit the number of parameters. A large number of parameter is a symptom of bad functional cohesion.
Functional cohesion: a function should perform only one operation.
Functional complexity: don't make function too complex: lines of code, control-flow complexity.
To reduce control-flow complexity, separate conditionals in different functions.
Methods and Support for Object Orientation
Overloading
Go does not have function or method overloading. Go Language FAQ says that "Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system."
The most useful feature of overloading, the call of function with optional arguments and inferring defaults for those omitted can be simulated using variadic functions.
Built-in Functions
Built-in functions are available by default, without importing any package. Their names are predeclared function identifiers. They give access to Go's internal data structures. Their semantics depends on the arguments.
Length and Capacity
len()
len()
returns string length, array length, slice length and map size.
cap()
cap()
returns slice capacity.
Allocation
Go has two allocation primitives that do different things and apply to different types: the built-in functions new()
and make().
new()
new(T)
allocates memory for the specified type, fills it with the zero value for the type and returns a pointer to the newly allocated memory, a value of type *T
. The memory allocated with new is automatically garbage collected.
var p *T
p = new(T)
new()
can be used to initialize structs. The following expressions are equivalent:
new(T)
*T{}
It is good practice to design the type to be usable with its zero values, right away, without additional initialization if possible. See:
In some cases, this is not possible. Slices, maps and channels are types whose zeroed values are not useful, they require initialization before use, and this is where make()
comes in. For example, new([]int)
returns a pointer to a nil
, while make(int[], 1, 10)
returns a slice value that can be used right away. See make()
below.
Note that conventionally some packages expose New()
functions to create the instances for their types. New()
functions are written by users who control their semantics.
make()
make(()
is a built-in function that can be used to create and initialize slices, maps and channels only. It is different from new()
in that it can be used with only these three types, initializes the instance to non-zero values, and returns a value of the type, not a pointer. The reason for the distinction is that these three types represent references to data structures that must be initialized before use. make()
initializes the internal data structures and prepares the value for use.