In the previous tutorials, we discussed basic programming like understanding loops or conditional statements, declaring variables or constants, etc. In all programs used to understand the concepts, we used a function. The function name is main, represented as main ( ). Here in this tutorial, you will learn about the types of functions, how to create a function, its return type, etc.
In Golang the execution of a program begins with the main function represented as func main ( ).
A function
is a set of similar statements or logical statements that are grouped together. Consider a simple daily example of making tea. In order to make tea, you need to follow a set of instructions like
So if we consider making a tea as a function with the above-mentioned steps as statements or instructions that need to be executed in a grouping fashion, all these statements will be executed together at each time. There may be some variation to these statements (steps) if some extra ingredients are added to the tea while preparing like ginger or cardamom etc. These variables can be input into the function. We will look at this part of how to pass those inputs and change flow in the functions incoming section of this tutorial.
In Golang to declare a function, you should use the keyword func
.
func
is followed by a name of the function which will be uppercase letters (capital) or lowercase letters (small) depending on the access level. Syntax to declare a function
func name(parameters){
body of statements
}
Where
Note: Need to be careful that the open curly bracket should be in the same line where the name of the function is declared, it cannot be in another line.
In go language, it is not allowed as in many other programming languages. Let us see a simple program
package main
import ("fmt")
// main function
func main() {
fmt.Println("I am main function ")
}
Output:
I am main function
Let us understand the concept of calling a function with the classic hello world program. Let us introduce a function hello, hello()
by using above explained syntax.
func hello() {
fmt.Println("Hello, World!")
}
Golang function with empty parentheses
We have created a function hello (). If you run this code inside a Go program it will not execute inside the program because our function is not fully defined. In order to execute and print or display the output, we need to call the function inside the main ( ) function of our program.
Let us see how to call the function hello()
inside of our main()
function block.
The program begins its execution from the main () function. The main() function appears only once in any program with package main which receives & returns no arguments. The below example shows the fully executable code that calls function hello() inside main()
Program to call a function
package main
import "fmt"
func main() { //main function
hello() //calling user defined function named hello
}
func hello() { //created function hello
fmt.Println("Hello World!")
}
Output:
Hello, World!
In the previous section, we discussed calling a function with empty parentheses. Let us learn how to use parameters inside a defined function parentheses. While defining arguments inside parentheses need to specify its corresponding data type too.
Golang function with arguments inside parentheses
Let us understand with the below example program. The program has a functioning site () with two parameters defined within parentheses. The first argument is of string data type called name and the second argument is of integer type called rept. When the function site ("Learn eTutorials", 5)
is called the control goes to func site where the set of instructions to be executed during the site function call is defined. The instruction provided inside the body is a for loop
which loops the name 5 times.
package main
import "fmt"
func main() {
site("Learn eTutorial", 5) // calling function with two parameters
}
func site(name string, rept int) {
for i := 0; i < rept; i++ {
fmt.Print("\n ",name)
}
}
Output:
Learn eTutorial Learn eTutorial Learn eTutorial Learn eTutorial Learn eTutorial
In Golang, functions can have any return type with any type of argument enclosed within function parenthesis. Let’s see how to declare a return type of function.
Syntax with return type
func name(parameters) <datatype of return type>{
body of statements
}
In the above syntax, the keyword func
defines a function followed by a function name
with arguments or parameters
enclosed within parenthesis till now is similar to the normal function declaration. In this syntax, we have mentioned a new thing that is the,return type of function
which can be int, float, a string of any data types we have discussed in basic data types.
let us understand with a program
package main
import "fmt"
func add(x int, y int) int { //add function
return x + y
}
func sub(x, y int) int { //sub function of omit type
return x - y
}
func main() {
fmt.Println(add(10, 5)) //calling function add
fmt.Println(sub(10, 5)) // calling function sub
}
Output:
15 5
Note: When the function parameters have the same datatype, that type can be omitted for one of the parameters, it is known as omit type
In the above program add () and sub() are two functions with two parameters of integer type. In add (),x & y are arguments of integer data type specified separately as int x, int y inside parentheses. In sub(), two arguments x & y are of integer type but only one argument is specified with the datatype. In such a case if both arguments have the same data types we can omit defining either of the argument data types.
It is understood in such a definition style the argument without datatype has a similar datatype of another argument mentioned inside parentheses. The type is omitted for variable x.
In Golang after function parameters, along with return type of function, named return variables can also be specified.
Let us understand with a program
package main
import "fmt"
func add(x int, y int) (a int) { //add function with return type variable a
a = x + y
return
}
func sub(x, y int) (b int) { //sub function of omit type & return variable b
b = x - y
return
}
func main() {
fmt.Println(add(10, 5)) //calling function add
fmt.Println(sub(10, 5)) // calling function sub
}
Output:
15 5
The above given code declares named variables a & b of integer type with respective add() and sub() functions. The calculation corresponding to each function is stored in variables and is returned with values using the return keyword. Once the main() function starts executing, calls the functions and displays the output as shown above.
Note: From the above programs we understood Golang supports multiple arguments in a function. Inside the function parenthesis, more than one argument can be passed.
func
is followed by a name of the function which will be uppercase letters (capital) or lowercase letters (small) depending on the access level. A function declared without any named identifier to refer to it is known as an anonymous function. Anonymous functions accept inputs and return outputs, similar to standard functions.
Program anonymous function
package main
import "fmt"
var (
add =func(x int, y int) (a int) { //add function with return type variable a
a=x + y
return
}
)
func main() {
fmt.Println(add(10, 5)) //calling function add
}
Output:
15