What is a function
A function is a block of code that can execute independently. A function has many benefits as outlined below
1. Promotes modularity
A large piece of code can be broken down into smaller functions which makes it modular.
2. Enhances reusability
If the same set of statements are required at multiple places, then they can be reused by grouping them into a function.
3. Better readability
All the code written in one place makes it uglier while a code logically divided into functions makes it easier to read and understand.
In this article, we will look at Golang functions, their syntax, creating and invoking functions with and without arguments with sufficient examples for clarity.
Functions in Golang are created using
func
keyword followed by a user-defined function name and parameters if required as shown below func <function name> (<parameters>) (<return types>) { // function body // return statement }
In the above definition,
a) func: keyword used to define a function
b) function name: User defined name of the function. This is the name with which the function will be invoked. Function name is followed by parenthesis.
c) parameters: Values that the function will receive when invoked. Parameters are optional.
If there are multiple parameters, then they should be separated by comma.
d) return types: A function may return a single or multiple values in Golang. This is the data types of values that the function will return.
Multiple return types are separated by a comma and enclosed between parenthesis.
Return types are also optional and are only required when the function returns a value.
Function body is enclosed between curly braces. A return statement is required at the end if the function is supposed to return some value.
Don’t worry, we will understand everything with examples.
Function example
Below is a function printMessage()
that prints a string.
func printMessage() { fmt.Println("Learning functions") }
This function does not receive any parameters and does not return any value.
Simply defining a function does not execute it. A function needs to be called or invoked in order to be executed and it is called by using its name followed by parenthesis.
Parenthesis will be empty if the function does not expect any arguments otherwise they should contain appropriate argument values separated by comma.
Below is an example that defines a function and invokes it.
package main import "fmt" // main function func main() { fmt.Println("Calling function...") // call function printMessage() } // function definition func printMessage() (int,string) { fmt.Println("Learning functions") }
This outputs
Calling function…
Learning functions
Function parameters
You may pass values to a function from the calling code. Function parameters are named variables along with their data types.
A function may accept any number of parameters separated by a comma. While invoking the function, the calling code needs to pass parameters in appropriate number and types.
Example of a function that accepts a string parameter is given below.
package main import "fmt" func main() { fmt.Println("Calling function...") // call function printMessage("Passed as parameter") } // function definition func printMessage(message string) { fmt.Println(message) }
Note that the function parameters are available inside a function as variables.
If the data type of parameter in the calling code does not match the type expected by the function, then an error is raised.
If you try to call the above function by passing a numeric argument as printMessage(1)
, then you get
cannot use 1 (type untyped int) as type string in argument to printMessage
or call it by passing two arguments as printMessage(“Test”, 1), then you get
too many arguments in call to printMessage
have (string, number)
want (string)
Error messages are self explanatory.
A function may return a value after performing its tasks such as the result of a computation. A function can return a value using
return
statement followed by the value to return. In order to return a value from a function, following two steps need to be followed
1. Declare that the function will return a value. This is done by writing the type of return value before the start of function body, that is, after the argument declaration and starting curly braces.
2. Write a return
statement at the end of function body followed by the return value. return
statement should be the last statement in a function body as shown below.
Example of a function that returns the sum of two integers is given below. Numbers to be added are passed as arguments.
package main import "fmt" func main() { fmt.Println("Adding values with a function...") // call function and assign return value result := add(5,7) fmt.Println("Sum is:", result) } func add(num1 int, num2 int) int { sum := num1 + num2 return sum }
In the calling code, if the value returned from a function is required, then it should be assigned to a variable as shown in the above example.
Output is given below
Adding values with a function…
Sum is: 12
Returning multiple values from function
In Go, a function may also return more than one values at the same time. For this,
1. Declare the data types of return values before function body. These types should be enclosed between parenthesis and separated by a comma.
2. Provide the values to be returned after return
statement separated by a comma.
Remember that the sequence of values after return should match their types in the declaration.
If the calling code requires the returned values, then they should be assigned to equal number of variables separated by a comma.
Example, below code declares a function that accepts two integers and returns their sum and product at the same time.
Look how the main()
function(calling code) defines two variables to hold the returned values
package main import "fmt" // main func main() { fmt.Println("Calling function with multiple return values...") // call function sum, product := printMessage(5, 7) fmt.Println("Sum is:", sum) fmt.Println("Product is:", product) } // function returning two values func printMessage(num1 int, num2 int) (int, int) { sum := num1 + num2 product := num1 * num2 // return two values return sum, product }
Calling function with multiple return values…
Sum is: 12
Product is: 35
In this example, the calling code must define an equal number of variables as the values returned by a function. Thus, in main()
, if you call the function as
sum := printMessage(5, 7)
you get
assignment mismatch: 1 variable but printMessage returns 2 values
Also, all declared variables should be used. Thus, if you call the function as
sum, product := printMessage(5, 7)
but do not use product
anywhere, then you get
product declared but not used
To solve this, Golang allows using blank identifiers in place of unused variables. A blank identifier is written using an underscore(_
).
So, above function call may be written as
sum, _ := printMessage(5, 7)
Now you are free to use only the first value.
Functions are very useful in creating reusable and maintainable code. Practice them to understand better.