Functions in Go Language
Overview
A function is simply a group of programming statements, When executed together they perform tasks in a step-by-step manner. functions also eliminate repetition of code and make the code reusable making them clean and ordered.
Introduction
Functions are a group of programming statements. Functions provide us with the concept of reusability which promotes code reusability, Reducing the usage of memory and development time. The function allows you to extract a commonly used block of code into a single component.
In Golang, Every code execution starts with the main() function which acts as an entry point for the execution flow.
Syntax
Function Declaration
The declaration of the function contains
- func: It is a keyword in the language, which is used to create a Golang function.
- function_name: It is the name of the function.
- Parameter-list: It contains the name and the type of the function inputs.
- Return_type: Returns types are optional in Golang. It contains details about what will a function return if we add a return type to our function, It is mandatory to pass a return value in our function.
Function Calling
Golang Function can be called in a below way.
Example
We will create an example of simple addition. A function add is created with the func keyword before it. the func keyword tells Go that this piece of code is a function. Later we invoked the function in the main() using its name.
Output:
Function Arguments
Call by Value
When we pass values of variables to a function as parameters, those functions are known as Call By Value. Changes made to the function variable won't update the original variables as we pass copies of those.
Output:
Call by Reference
While Calling a function, If we pass the address of a variable instead of a value, Those functions are known as Call by Reference. Changes made to function variables update the original variables as we are passing the addresses of those.
Output:
More Examples
Let's see more examples of the Golang function.
Golang Functions Returning Multiple Values
Output:
The Return Values of a Function can be Named in Golang
Output:
Golang Passing Address to a Function
Output:
Anonymous Functions in Golang
Output:
Conclusion
- Understood the concept of functions and studied the syntax and declaration of functions.
- Created a vast number of function examples.
- understood the concept of call by value and call by reference with examples.